Summary - Readonly
- TypeScript course
- Intermediate
- Lesson 14/89
- 4 min
Write an immutable configuration with readonly fields.
Summary - Readonly
A Settings class creates an immutable configuration model with readonly fields. Each field is assigned in the constructor and frozen afterwards; this keeps the configuration consistent.
class Settings {
readonly env: string;
readonly version: number;
constructor(env: string, version: number) {
this.env = env;
this.version = version;
}
}
const s = new Settings("prod", 2);
console.log(s.env);
console.log(s.version);Practice Settings class with readonly fields
Define a Settings class with readonly env: string and readonly version: number fields. Add a constructor that takes env and version parameters and assigns them with this. Create a new Settings("prod", 2) and print env and version.
Starter code
// Settings sınıfı tanımla (değiştirilemez ortam ve sürüm alanları)
// constructor ile env ve version al, this ile ata
// yeni Settings oluştur, env ve version yazdırSample solution
class Settings {
readonly env: string;
readonly version: number;
constructor(env: string, version: number) {
this.env = env;
this.version = version;
}
}
const s = new Settings("prod", 2);
console.log(s.env);
console.log(s.version);Expected output
prod 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In which cases can a readonly field be assigned?
- From outside, always
- Inside a method
- At declaration or in the constructor Correct answer
- Only in a static method
Explanation: A readonly field can only be assigned at its declaration (initial value) or inside the constructor. Methods, external code, or static methods cannot assign it.
2 Complete the readonly env field
class Settings {
____ env: string;
readonly version: number;
constructor(env: string, version: number) {
this.env = env;
this.version = version;
}
}
class Settings {
readonly env: string;
readonly version: number;
constructor(env: string, version: number) {
this.env = env;
this.version = version;
}
}
Explanation: You write readonly so that the env field is immutable. const is invalid in a class, private restricts access (mutable), and static moves to the class level (mutable).
3 Settings parts
| Term | Meaning |
|---|---|
readonly env |
Immutable environment |
readonly version |
Immutable version |
new Settings("prod", 2) |
Instance creation |
s.env |
Read configuration |