TypeScript の型の絞り込みメモ
ユリア 10219ee912421f0b · · English · 中文

TypeScript の型の絞り込みメモ

型の絞り込みは毎日使うのに、どれを選ぶかいつも考えてしまう。

よくある3つの形

// 1. プリミティブ:typeof
function pad(x: string | number) {
  if (typeof x === "string") return x.padStart(8, "0");
  return String(x).padStart(8, "0");
}

// 2. オブジェクトの形:in
function area(s: { r: number } | { w: number; h: number }) {
  if ("r" in s) return Math.PI * s.r ** 2;
  return s.w * s.h;
}

// 3. おすすめ:判別可能なユニオン
type Shape =
  | { kind: "circle"; r: number }
  | { kind: "rect"; w: number; h: number };

判別可能なユニオンを switch と never のフォールバックに組み合わせれば、新しいバリアントを追加したときに未処理をコンパイラが教えてくれる——それが一番の利点です。