JS Built-ins
TypeScriptbeginner

Utility Types β€” Readonly<T>

πŸ“– Usage Example
type Config = Readonly<{ host: string; port: number }>
const c: Config = { host: 'localhost', port: 3000 }
// c.host = 'other'  β†’ Error: cannot assign to read-only property

Readonly<T> makes every property of T immutable at the TypeScript type level.

Utility Types: Readonly<T>

Readonly<T> marks all properties as non-writable at the type level.

Challenge: Implement createReadonly<T extends object>(obj: T): Readonly<T> that prevents mutations using Object.freeze.

const ro = createReadonly({ x: 1, y: 2 })
ro.x  // β†’ 1  (but writing would throw in strict mode)
πŸ’‘ Hints (1)
  • β€’ Object.freeze prevents property mutation at runtime.