union 타입을 switch 안에서 사용할 때, 다루지 않는 타입에 대해서 컴파일 에러를 내고 싶으면 ts-pattern 라이브러리를 사용하곤 했었다. 이제 라이브러리 없이도 간단하게 switch문 안에서 컴파일 에러를 낼 수 있을 것 같다.
https://type-level-typescript.com/types-are-just-data
/**
* Type the `exhaustive` function so that it cannot be
* called except in unreachable code branches.
*/
namespace exhaustive {
function exhaustive(...args: never[]) {}
const HOURS_PER_DAY = 24
// Since `HOURS_PER_DAY` is a `const`, the next
// condition can never happen
// ✅
if (HOURS_PER_DAY !== 24) exhaustive(HOURS_PER_DAY);
// Outside of the condition, this should
// return a type error.
// @ts-expect-error ❌
exhaustive(HOURS_PER_DAY);
const exhautiveCheck = (input: 1 | 2) => {
switch (input) {
case 1: return "!";
case 2: return "!!";
// Since all cases are handled, the default
// branch is unreachable.
// ✅
default: exhaustive(input);
}
}
const nonExhautiveCheck = (input: 1 | 2) => {
switch (input) {
case 1: return "!";
// the case where input === 2 isn't handled,
// so `exhaustive` shouldn't be called.
// @ts-expect-error ❌
default: exhaustive(input);
}
}
}