🐈
[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);
}
};
参考
Discussion