Skip to content

Instantly share code, notes, and snippets.

@jantimon
Created July 20, 2018 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jantimon/77501cc209663252cece26085be6ce23 to your computer and use it in GitHub Desktop.
Save jantimon/77501cc209663252cece26085be6ce23 to your computer and use it in GitHub Desktop.
Typescript Prevent Default Case
interface Box {
height: number;
width: number;
color: 'RED' | 'BLUE'
}
function logColor(box: Box) {
switch (box.color) {
case 'RED':
console.log(box, 'is red');
break;
case 'BLUE':
console.log(box, 'is blue');
break;
default:
return throwBadKind(box.color);
}
}
function throwBadKind(x: never): never {
throw new Error('Unknown type "' + (x as string) + "'");
}
@jantimon
Copy link
Author

jantimon commented Jul 20, 2018

Typescript will not allow data to get into the default case.

Try it yourself in playground

To see the typing error add a new color in line 4 or remove case 'BLUE' in line 12-14.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment