💡

ありえない状態がありえないように型を定義する

2023/11/30に公開

下記はTypeScriptでの例です。
ユニオン型を使うことでより厳密な型定義ができます。

type Rice = {
  name: string;
  milling: "玄米" | "白米";
};

type Vegetable = {
  name: string;
  eating: "生食" | "加熱";
};

type StrictFood = Rice | Vegetable;

type UnstrictFood = {
  name: string;
  milling?: "玄米" | "白米";
  eating?: "生食" | "加熱";
};

const invalid = {
  name: "コシヒカリ",
};

// エラーになる
// Type '{ name: string; }' does not satisfy the expected type 'StrictFood'. Property 'eating' is missing in type '{ name: string; }' but required in type 'Vegetable'.
invalid satisfies StrictFood;

// エラーにならない
invalid satisfies UnstrictFood;

参考
https://speakerdeck.com/naoya/guan-shu-xing-puroguramingutoxing-sisutemunomentarumoderu
https://slides.com/kawasima/truth-of-data-oriented-programming
https://zenn.dev/estra/articles/typescript-type-set-hierarchy

Discussion