Created
January 4, 2019 20:45
-
-
Save JanMalch/66f642ab22c96aae060c7029fbe54d68 to your computer and use it in GitHub Desktop.
Exhaustive switch in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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