TypeScript
/Intermediate
Readonly Properties
Definition
The `readonly` modifier makes an object property or an entire array immutable in TypeScript, preventing reassignment after initialization.
Explain Like I'm New
If an object is a museum exhibit, `readonly` is the 'Do Not Touch' glass case around a specific artifact. You can look at it, but the compiler will throw an error if you try to change its value.
Real World Example
Database IDs. When you fetch a user from the DB, their `id` shouldn't change. `type User = { readonly id: number; name: string }`.
Common Use Cases
- •Preventing accidental mutation
- •Redux state definitions
- •Functional programming patterns
Interactive Example
Loading Code Playground...
Interview Questions
basic
- How do you make a property readonly?
intermediate
- Is `readonly` enforced at runtime in the browser?
advanced
- What is the difference between `readonly string[]` and `ReadonlyArray<string>`?