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 ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.