TypeScript: Exhaustive Switch Helper
TypeScriptMake the compiler tell you when a union gains a case.
TypeScript · 12 lines
copied 9 times
function assertNever(x: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}
function label(status: 'todo' | 'doing' | 'done') {
switch (status) {
case 'todo': return 'To do';
case 'doing': return 'In progress';
case 'done': return 'Done';
default: return assertNever(status);
}
}
4
Fire
1
Learned something
2
Saved me time
0
Mind-blown
Sign in to react and star