Strict Class Initialization

TypeScript 2.7 introduces a new flag called —strictPropertyInitialization.This flag performs checks to ensure that each instance property of a class gets initialized in the constructor body, or by a property initializer.For example

  1. class C {
  2. foo: number;
  3. bar = "hello";
  4. baz: boolean;
  5. // ~~~
  6. // Error! Property 'baz' has no initializer and is not definitely assigned in the
  7. // constructor.
  8. constructor() {
  9. this.foo = 42;
  10. }
  11. }

In the above, if we truly meant for baz to potentially be undefined, we should have declared it with the type boolean | undefined.

There are certain scenarios where properties can be initialized indirectly (perhaps by a helper method or dependency injection library), in which case you can use the new definite assignment assertion modifiers for your properties (discussed below).

  1. class C {
  2. foo!: number;
  3. // ^
  4. // Notice this '!' modifier.
  5. // This is the "definite assignment assertion"
  6. constructor() {
  7. this.initialize();
  8. }
  9. initialize() {
  10. this.foo = 0;
  11. }
  12. }

Keep in mind that —strictPropertyInitialization will be turned on along with other —strict mode flags, which can impact your project.You can set the strictPropertyInitialization setting to false in your tsconfig.json’s compilerOptions, or —strictPropertyInitialization false on the command line to turn off this checking.