1. Introduction
The readonly modifier marks a class property as immutable after its initial assignment. It is a compile-time guarantee that helps prevent accidental reassignment of values that should stay constant for the lifetime of an object, such as an ID or a configuration URL.
Cricket analogy: A Player class's readonly playerId is like a BCCI-issued registration number assigned once and never altered, guarding against accidental reassignment the way readonly prevents overwriting a fixed value.
2. Syntax
class ClassName {
readonly propertyName: Type;
readonly propertyWithDefault: Type = defaultValue;
constructor(propertyName: Type) {
this.propertyName = propertyName; // allowed here
}
}3. Explanation
A readonly property can be assigned in exactly two places: at its declaration (giving it a default value) or inside the constructor of the same class. Any attempt to assign to it afterward — in a method, or from outside the class — is flagged as a compile-time error by TypeScript.
Cricket analogy: A readonly debutSeason can be set at declaration or inside the Player constructor when the object is built, but any later attempt from a method like transferTeam() to reassign it is flagged as a compile error.
readonly is different from const: const applies to variable bindings, while readonly applies to object and class properties. Also note that readonly only prevents reassigning the property reference itself; if the value is an object or array, its internal contents can still be mutated unless it is also deeply frozen.
Cricket analogy: Unlike const totalOvers = 50, which binds a variable, readonly seasonWins protects a class property on a Team object; and if that property holds a mutable squadList array, individual player entries inside can still be swapped unless deeply frozen.
readonly can only be assigned inside the constructor or at declaration — never in a regular method, even a method called immediately after construction. Attempting this.apiUrl = newUrl; in any other method produces the compiler error: "Cannot assign to 'apiUrl' because it is a read-only property."
4. Example
class Config {
readonly apiUrl: string;
readonly maxRetries: number = 3;
constructor(apiUrl: string) {
this.apiUrl = apiUrl; // allowed inside constructor
}
}
const config = new Config("https://api.example.com");
console.log(config.apiUrl);
console.log(config.maxRetries);
// config.apiUrl = "https://other.com";
// Error: Cannot assign to 'apiUrl' because it is a read-only property.5. Output
https://api.example.com
36. Key Takeaways
- readonly properties can only be assigned at declaration or inside the constructor.
- Any later reassignment, inside or outside the class, is a compile-time error.
- readonly is for object/class properties; const is for variable bindings.
- readonly prevents reassigning the reference, not deep mutation of an object/array value.
- readonly can be combined with parameter property shorthand, e.g. constructor(readonly id: string).
Practice what you learned
1. Where can a readonly class property legally be assigned a value?
2. What error would `config.apiUrl = "https://other.com";` produce after Config has been constructed?
3. What is the key difference between 'const' and 'readonly' in TypeScript?
4. If a readonly property holds an array, e.g. `readonly items: string[] = []`, what can still be done to it?
5. What does console.log(config.maxRetries) print given `readonly maxRetries: number = 3;` and no constructor override?
Was this page helpful?
Previous
Access Modifiers in TypeScript (public, private, protected)
Next
Abstract Classes in TypeScript
You May Also Like
Classes in TypeScript
Learn how TypeScript classes add type-checked properties, methods, and constructor parameter property shorthand on top of ES2015 classes.
Access Modifiers in TypeScript (public, private, protected)
Control the visibility of class members with public, private, and protected, and understand that these checks exist only at compile time.
Optional and Readonly Properties in TypeScript
Learn how to mark object properties as optional with `?` and immutable with `readonly`, and understand the compile-time-only nature of these guarantees.
Static Members in TypeScript
Define properties and methods that belong to the class itself rather than to individual instances, using the static keyword.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics