What is the readonly modifier in TypeScript?
Answer
The readonly modifier prevents a property from being changed after it is initialized. It can be applied to interface properties, class properties, and tuple elements. Interface: interface Point { readonly x: number; readonly y: number; } — you can create a Point but cannot reassign x or y afterwards. Class: class Circle { readonly radius: number; constructor(r: number) { this.radius = r; } } — radius can only be set in the constructor. Readonly arrays: const arr: readonly number[] = [1, 2, 3]; — prevents push, pop, and reassignment. Readonly utility type: Readonly<T> makes all properties of T readonly: type ReadonlyUser = Readonly<User>. Note: readonly is a compile-time-only check — it does not create a frozen object at runtime. For deep immutability at runtime, use Object.freeze() or libraries like Immer. Use readonly liberally — it communicates intent and prevents accidental mutations.
Previous
What are optional properties and parameters in TypeScript?
Next
What is a type assertion in TypeScript?