Skip to content

Instantly share code, notes, and snippets.

@JanMalch
Created January 4, 2019 20:45
Show Gist options
  • Save JanMalch/66f642ab22c96aae060c7029fbe54d68 to your computer and use it in GitHub Desktop.
Save JanMalch/66f642ab22c96aae060c7029fbe54d68 to your computer and use it in GitHub Desktop.
Exhaustive switch in TypeScript
// Add and use this function to get compile time errors if your switches are not exhaustive.
export function unreachable(value: never, message = `No such case in exhaustive switch: ${value}`) {
throw new Error(message);
}
// Usage
enum FooBar {
foo,
bar,
fooBar
}
switch (example) {
case FooBar.foo:
return 'Foo';
case FooBar.bar:
return 'Bar';
case FooBar.fooBar:
return 'FooBar';
default:
return unreachable(example);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment