中級 › is possibly 'undefined' の原因と直し方 › パターン4
is possibly 'undefined' の原因と直し方
interfaceで?を付けたオプショナルプロパティは、値が入っていない(undefined)可能性を型として保持します。
1 interface Account { 2 nickname?: string; 3 } 4 function shout(a: Account): string { 5 return a._________.toUpperCase(); ^ 6 } 7 console.log(shout({ nickname: "al" }));
main.ts(5,10): error TS18048: 'a.nickname' is possibly 'undefined'.
空欄を埋めてコンパイルを通す
nicknameはオプショナルプロパティなのでundefinedかもしれません。narrowingせずにtoUpperCase()を呼ぶとエラーになります。
次の問題