読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
蓮さんのコードには、よく似た関数が2つあります。
const firstProduct = (items: readonly Product[]): Product | undefined => items[0];
const firstReservation = (items: readonly Reservation[]): Reservation | undefined => items[0];
どちらも「配列の最初の値を返す」処理で、違うのは型だけです。1つにまとめようとして、any を使ってみます。
const first = (items: readonly any[]): any => items[0];
const p = first(products);
p.prise;
// エラーにならない
any を使うと1つにまとまりますが、戻り値も any になり、prise のつづりのまちがいに気づけません。
| 書き方 | まとめられるか | 戻り値の型 |
|---|---|---|
| 型ごとに関数を書く | まとめられない | 正しい型 |
any で書く | まとめられる | any(型チェックが止まる) |
| ジェネリクスで書く | まとめられる | 正しい型 |
2 / 16