- Learning TypeScript 2.x
- Remo H. Jansen
- 268字
- 2025-04-04 17:02:05
Strict property initialization
Since the release of TypeScript 2.7, a compile-time error will be thrown if strict mode is enabled and we forget to initialize one of the properties of a class. For example, the following class initializes the property named height using a method, and the property named width using its constructor. TypeScript knows that if an instance of the class is created, a value will be assigned to the width property. However, it has no way to ensure that a value is assigned to the height property. If strict mode is enabled, an error will be thrown:
class Rectangle { public width: number; public height: number; // Error public constructor(width: number) { this.width = width; } public setHeight(height: number) { this.height = height; } }
We can use the ! operator to let TypeScript know that we don't want an error to be thrown:
class Rectangle { public width: number; public height!: number; // OK public constructor(width: number) { this.width = width; } public setHeight(height: number) { this.height = height; } }
It is very common to encounter this compilation error when we define a class without a constructor:
class Rectangle { public width: number; // Error public height: number; // Error }
We can use the ! operator to solve the compile-time error when we don't want to define a constructor:
class Rectangle { public width!: number; // OK public height!: number; // OK }
Alternatively, we can initialize the properties with a default value:
class Rectangle6 { public width: number = 0; // OK public height: number = 0; // OK }