オブジェクトの型のオプションプロパティ (optional property)
TypeScriptで、オブジェクトプロパティのオプショナルを型付けするには、プロパティ名の後ろに?を書きます。
tstypeSize = {width ?: number;};
tstypeSize = {width ?: number;};
オプションプロパティを持ったオブジェクトの型には、そのオプションプロパティを持たないオブジェクトを代入できます。
tsconstsize :Size = {}; // OK
tsconstsize :Size = {}; // OK
また、オプションプロパティの値がundefinedのオブジェクトも代入できます。
tsconstsize :Size = {width :undefined ,}; // OK
tsconstsize :Size = {width :undefined ,}; // OK
しかし、オプションプロパティの値がnullの場合は代入できません。
tsconstsize :Size = {Type 'null' is not assignable to type 'number | undefined'.2322Type 'null' is not assignable to type 'number | undefined'.: null, width };
tsconstsize :Size = {Type 'null' is not assignable to type 'number | undefined'.2322Type 'null' is not assignable to type 'number | undefined'.: null, width };
ただしstrictNullChecksを無効にしている場合はnullも代入できるようになります。
strictNullChecksがfalseの場合tsconstsize :Size = {width : null,};
strictNullChecksがfalseの場合tsconstsize :Size = {width : null,};
関連情報
📄️ オプショナルチェーン
JavaScriptのオプショナルチェーン?.は、オブジェクトの参照がnullやundefinedの場合でも、エラーを起こさずにプロパティを参照できる安全な方法です。
📄️ strictNullChecks
null・undefinedのチェックを厳しくする