Readonly parameter
- TypeScript course
- Intermediate
- Lesson 12/89
- 4 min
Learn to use readonly in constructor parameters.
readonly parameter
readonly can also be written on a constructor parameter; this is a parameter property. The field is created automatically, becomes readonly, and is assigned the parameter value. You do not need to write this.x = x in the body.
class Point {
constructor(readonly x: number, readonly y: number) {}
}
const p = new Point(3, 4);
console.log(p.x);Long form equivalent
When not using a parameter property, you achieve the same result with the long form: declare the field with readonly and assign it with this in the constructor body. Both forms provide the same immutability.
class Point {
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}Practice Point class with readonly fields
Define a Point class with readonly x: number and readonly y: number fields. Add a constructor that takes x and y parameters and assigns them with this. Create a new Point(3, 4) and print the x field.
Starter code
// Point sınıfı tanımla (değiştirilemez x ve y alanları)
// constructor ile x ve y al, this ile ata
// yeni Point oluştur, x'i yazdırSample solution
class Point {
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const p = new Point(3, 4);
console.log(p.x);Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when you write constructor(readonly apiKey: string)?
- Only the parameter becomes readonly
- The class gives an error
- apiKey becomes static
- The apiKey field is auto-created and becomes readonly Correct answer
Explanation: A readonly parameter property auto-defines the field and makes it readonly. It cannot be changed outside the constructor; you do not need to write this.apiKey = apiKey.
2 Complete the readonly field
class Point {
____ x: number;
constructor(x: number) {
this.x = x;
}
}
class Point {
readonly x: number;
constructor(x: number) {
this.x = x;
}
}
Explanation: You write readonly so that the x field is immutable. const is invalid in a class body, public and private control access (still mutable).
3 Readonly parameter parts
| Term | Meaning |
|---|---|
constructor(readonly x: number) |
Shorthand (parameter property) |
readonly x: number |
Long form (field declaration) |
this.x = x |
Constructor assignment |
p.x |
External read |