🐈

[TypeScript]switch文の条件がユニオン型のときcaseの実装が漏れていたらコンパイルエラーになるようにする

に公開
type Animal = "cat" | "dog" | "bird";

const assertNever = (x: never): never => {
  throw new Error("Unexpected object: " + x);
};

const getAnimalSound = (animal: Animal) => {
  switch (animal) {
    case "cat":
      return "meow";
    case "dog":
      return "woof";
    case "bird":
      return "tweet";
    default:
      assertNever(animal);
  }
};

const getAnimalSoundCompileError = (animal: Animal) => {
  switch (animal) {
    case "cat":
      return "meow";
    case "dog":
      return "woof";
    default:
      // コンパイルエラーになる
      // Argument of type 'string' is not assignable to parameter of type 'never'.
      assertNever(animal);
  }
};

参考
https://typescriptbook.jp/reference/statements/switch
https://typescriptbook.jp/reference/values-types-variables/discriminated-union

Discussion