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
interface Configuration { readonly apiKey: string; theme: string; } const myConfig: Configuration = { apiKey: "12345-ABCDE", theme: "dark" }; myConfig.theme = "light"; // Allowed // myConfig.apiKey = "999"; // ERROR: Cannot assign to 'apiKey' because it is a read-only property. // Readonly Arrays const strictList: readonly number[] = [1, 2, 3]; // strictList.push(4); // ERROR: Property 'push' does not exist on type 'readonly number[]'.
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>`?