strictPropertyInitialization
strictPropertyInitializationはクラスプロパティの初期化を必須にするコンパイラオプションです。
- デフォルト: strictが有効の場合は
true、それ以外はfalse - 追加されたバージョン: 2.7
- TypeScript公式が有効化推奨
注意
このオプションを効かすにはstrictNullChecksもtrueする必要があります。
解説
strictPropertyInitializationをtrueにすると、値が初期化されていないクラスプロパティについて警告を出します。
tsclassFoo {Property 'prop' has no initializer and is not definitely assigned in the constructor.2564Property 'prop' has no initializer and is not definitely assigned in the constructor.: number; prop }
tsclassFoo {Property 'prop' has no initializer and is not definitely assigned in the constructor.2564Property 'prop' has no initializer and is not definitely assigned in the constructor.: number; prop }
初期化は、次のいずれかで行う必要があります。
- コンストラクタで初期化
- 初期化子で初期化
- undefinedとのユニオン型で型注釈する
次は、コンストラクタで初期化する例です。
tsclassFoo {prop : number;constructor() {this.prop = 1;}}
tsclassFoo {prop : number;constructor() {this.prop = 1;}}
次は、初期化子で初期化する例です。
tsclassFoo {prop : number = 1;// ^^^初期化子}
tsclassFoo {prop : number = 1;// ^^^初期化子}
プロパティの型がundefinedとのユニオン型の場合、初期化しなくても警告が出ません。
tsclassFoo {prop : number | undefined;}
tsclassFoo {prop : number | undefined;}
プロパティがオプションの場合も警告が出ません。
tsclassFoo {prop ?: number;}
tsclassFoo {prop ?: number;}
学びをシェアする
TypeScriptのstrictPropertyInitializationはプロパティの初期化を必須にするコンパイラオプション。
⚠️strictNullChecksもtrueする必要あり
✅コンストラクタで初期化OR初期化子が必須になる
🙆🏻♂️undefinedとのユニオン型で型注釈するのはOK
『サバイバルTypeScript』より
関連情報
📄️ strict
strict系のオプションを一括で有効化する
📄️ フィールド
JavaScriptでインスタンスにフィールドを持たせるには、インスタンス化したオブジェクトのプロパティに値を代入します。