readonly fields
- TypeScript course
- Intermediate
- Lesson 11/89
- 4 min
Learn to make class fields constant with readonly.
What is readonly?
readonly makes a class field immutable. The field can only be assigned at its declaration (initial value) or inside the constructor; assigning it anywhere else causes a compile error.
class Config {
readonly apiKey: string;
constructor(apiKey: string) {
this.apiKey = apiKey;
}
}
const c = new Config("abc123");
// c.apiKey = "xyz"; // error
console.log(c.apiKey);readonly and strict mode
Under strict mode, readonly fields must also be given an initial value or assigned in the constructor. After the first assignment, the field is frozen and no method or external code can change it.
class Config {
readonly version: number = 1;
readonly name: string;
constructor(name: string) {
this.name = name;
}
}Practice Config class with a readonly field
Define a Config class with a readonly apiKey: string field. Add a constructor that takes apiKey and assigns it with this. Create a new Config("abc123") and print the apiKey field.
Starter code
// Config sınıfı tanımla (değiştirilemez api anahtarı)
// constructor ile apiKey al, this ile ata
// yeni Config oluştur, apiKey'i yazdırSample solution
class Config {
readonly apiKey: string;
constructor(apiKey: string) {
this.apiKey = apiKey;
}
}
const c = new Config("abc123");
console.log(c.apiKey);Expected output
abc123
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you try to change a readonly field outside the constructor?
- Compile error Correct answer
- It works
- Runtime error
- Returns undefined
Explanation: A readonly field can only be assigned in its declaration or inside the constructor. Trying to assign it outside the constructor causes a compile error; it does not wait until runtime.
2 Complete the readonly modifier
class Config {
____ apiKey: string = "abc";
}
class Config {
readonly apiKey: string = "abc";
}
Explanation: readonly makes the field immutable. const is invalid in a class body, static moves to the class level (still mutable), and private restricts access (still mutable).
3 readonly parts
| Term | Meaning |
|---|---|
readonly |
Immutable field |
constructor |
Where readonly assignment is allowed |
c.apiKey |
External read |
c.apiKey = "xyz" |
External assignment (error) |