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