中級 › is possibly 'undefined' の原因と直し方 › パターン2
is possibly 'undefined' の原因と直し方
interfaceで?を付けたオプショナルプロパティは、値が入っていない(undefined)可能性を型として保持します。
1 interface Cart { 2 coupon?: string; 3 } 4 function applyCoupon(c: Cart): number { 5 return c._______.length; ^ 6 } 7 console.log(applyCoupon({ coupon: "SAVE10" }));
main.ts(5,10): error TS18048: 'c.coupon' is possibly 'undefined'.
空欄を埋めてコンパイルを通す
couponもオプショナルなのでundefinedの可能性があります。lengthへアクセスする前に確認が必要です。
次の問題