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