読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
割引を、省略できる引数にします。
const calcTotal = (subtotal: number, discount?: number): number => {
if (discount === undefined) {
return subtotal;
}
return subtotal - discount;
};
calcTotal(820);
// 820
calcTotal(820, 50);
// 770
discount?: number の引数は、関数の中では number | undefined になります。そのまま subtotal - discount と書くとエラーになるので、undefined かどうかを確かめます。
渡されなかったときの値が決まっているなら、既定値を書くほうが簡単です。
const calcTotal = (subtotal: number, discount = 0): number => {
return subtotal - discount;
};
| 書き方 | 関数の中の型 | 使う場面 |
|---|---|---|
discount?: number | number | undefined | 渡されたかどうかで処理を変える |
discount = 0 | number | 渡されなければ決まった値を使う |
既定値を書くと、型は値から推論されます。discount = 0 なら number です。
6 / 16