$ ryokkkke.com/TypeScript/tsconfig.json

strictPropertyInitialization

概要

https://www.typescriptlang.org/tsconfig#strictPropertyInitialization

{
  "strictPropertyInitialization": true
}

クラス定義時、インスタンス変数の初期化が、

  • 宣言時
  • コンストラクタ

のどちらでも行われていない場合にエラーにします。

TypeScript2.7 で導入されました。

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2–7.html

詳しく

class C {
  foo: number;
  bar = "hello";
  baz: boolean;

  constructor() {
    this.foo = 42;
  }
}
error TS2564: Property 'baz' has no initializer and is not definitely assigned in the constructor.

このbazは宣言時にもコンストラクタでも初期化されていません。

エラーを回避するためには、

baz: boolean = false;

このように宣言時に初期化するか、もしくは

  constructor() {
    this.foo = 42;
    this.baz = false;
  }

コンストラクタで初期化するようにします。

また、!(Definite Assignment Assertion Modifier)を変数宣言時につけることで、強制的にエラーを消すことができます。

これは、DI などで外部から代入されることを想定している場合などに役立ちます。
とはいえ、Non-null Assertion Operator をあまり使わないようにするのと同様に、基本的には初期化するという正当な方法でエラーを回避するべきでしょう。