Readonly Properties
Prevent a property from being changed after the object is created.
Syntax
interface User { readonly id: number; }Prefix a property with readonly to lock it after creation. You can read it, but assigning to it later is a compile error.
This is great for identifiers and other values that should never change once set.
Example
Loading editor…
Press Run to execute the code.
When to use it
- An entity's id property is readonly so it can be set on creation but never accidentally overwritten later.
- A config object loaded at startup is typed with readonly on every field to prevent mutations across modules.
- A value object representing money uses readonly amount and currency so the domain model stays immutable.
More examples
Readonly property on interface
Marks id as readonly so it can be initialised but never changed, while name remains mutable.
interface User {
readonly id: number;
name: string;
}
const user: User = { id: 1, name: 'Alice' };
user.name = 'Bob'; // OK — not readonly
user.id = 2; // Error: Cannot assign to 'id' because it is a read-only propertyReadonly with const assertion
Uses as const to make all properties deeply readonly without needing to explicitly annotate each one.
const config = {
apiUrl: 'https://api.example.com',
maxRetries: 3,
} as const;
// config.apiUrl = 'other'; // Error: Cannot assign to 'apiUrl' because it is a read-only propertyReadonly class property
Demonstrates a readonly class property that can only be assigned inside the constructor, never mutated afterwards.
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius; // only writable in constructor
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
Discussion