読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
型ガードは、filter と組み合わせても使えます。
const ids = ["p001", "p999", "p002"];
const found = ids.map((id) => products.find((p) => p.id === id));
// found は (Product | undefined)[]
const isDefined = <T>(value: T | undefined): value is T => value !== undefined;
const existing = found.filter(isDefined);
// existing は Product[]
isDefined の <T> は、「どんな型でもよい」ことを表す書き方で、ジェネリクスと呼びます。ジェネリクスは、カリキュラム「TypeScript実践:型設計のベストプラクティス」で詳しく扱います。ここでは、「undefined を取り除く型ガード」として使います。
TypeScript 5.5 以降では、found.filter((p) => p !== undefined) と書くだけでも、Product[] に推論されます。
const isReservationStatus = (value: string): value is ReservationStatus => value === "reserved" || value === "picked_up" || value === "cancelled"; と書きます。
16 / 17