Concept Flow - Readonly properties
Define object with readonly property
Try to assign new value to readonly property
This flow shows that once a readonly property is set, trying to change it causes an error and stops the program.
interface Person {
readonly name: string;
}
const p: Person = { name: "Alice" };
p.name = "Bob"; // Error| Step | Action | Property 'name' Value | Result |
|---|---|---|---|
| 1 | Create object p with name = 'Alice' | 'Alice' | Object created successfully |
| 2 | Attempt to assign p.name = 'Bob' | 'Alice' | Error: Cannot assign to 'name' because it is a read-only property |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| p.name | undefined | 'Alice' | 'Alice' (unchanged due to error) |
Readonly properties in TypeScript: - Use 'readonly' keyword in interfaces or classes - Property can be set once during object creation - Cannot be changed later; assignment causes error - Helps protect data from accidental changes - Compile-time error if reassigned
readonly keyword do in TypeScript?readonlyreadonly keyword is used to mark properties that cannot be changed after initialization.readonly means no changes allowed after set [OK]id in a TypeScript class?readonly before the property name.readonly id: number; which is correct. const id: number; uses const which is invalid inside class properties. private readonly id: number; adds private which is valid but not asked for. id readonly: number; has wrong order.class User {
readonly name: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User('Alice');
user.name = 'Bob';
console.log(user.name);name is marked readonly, so it cannot be assigned a new value after construction.user.name = 'Bob'interface Point {
readonly x: number;
y: number;
}
const p: Point = { x: 10, y: 20 };
p.x = 15;
console.log(p.x);x is readonly in the interface, so assigning p.x = 15 is not allowed.Config where the version property is set once during construction and never changes, but settings can be updated anytime. Which is the best way to declare these properties?version should be readonly (set once, no changes). The settings should be mutable (can change anytime).version as readonly and leaves settings mutable. version: string; readonly settings: object; reverses roles. readonly version: string; readonly settings: object; makes both readonly. version: string; settings: object; makes both mutable.Pass the test and this pattern moves unknown