0
0
Typescriptprogramming~10 mins

Readonly properties in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Typescript
interface Person {
  readonly name: string;
}

const p: Person = { name: "Alice" };
p.name = "Bob"; // Error
This code defines a readonly property 'name' and then tries to change it, which causes an error.
Execution Table
StepActionProperty 'name' ValueResult
1Create object p with name = 'Alice''Alice'Object created successfully
2Attempt to assign p.name = 'Bob''Alice'Error: Cannot assign to 'name' because it is a read-only property
💡 Execution stops at step 2 due to assignment error on readonly property
Variable Tracker
VariableStartAfter Step 1After Step 2
p.nameundefined'Alice''Alice' (unchanged due to error)
Key Moments - 2 Insights
Why can't we change the value of a readonly property after the object is created?
Readonly properties are designed to prevent changes after initialization. As shown in execution_table step 2, trying to assign a new value causes a compile-time error, so the value stays the same.
Does readonly mean the property cannot be set at all?
No, readonly means the property can be set once when the object is created (step 1), but cannot be changed later (step 2).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p.name after step 2?
A'Bob'
B'Alice'
Cundefined
Dnull
💡 Hint
Check the 'Property 'name' Value' column at step 2 in execution_table
At which step does the error occur when trying to change the readonly property?
AStep 1
BNo error occurs
CStep 2
DAfter execution ends
💡 Hint
Look at the 'Result' column in execution_table for the error message
If we remove 'readonly' from the property, what would happen at step 2?
AValue changes to 'Bob' successfully
BError still occurs
CObject creation fails
DProperty becomes undefined
💡 Hint
Think about how readonly affects assignment shown in execution_table
Concept Snapshot
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
Full Transcript
This visual execution shows how readonly properties work in TypeScript. First, an object with a readonly property 'name' is created and set to 'Alice'. Then, an attempt to change 'name' to 'Bob' causes a compile-time error, so the value remains 'Alice'. Readonly means you can set the property once but cannot change it later. This prevents accidental changes to important data.