Created
July 20, 2018 10:09
-
-
Save jantimon/77501cc209663252cece26085be6ce23 to your computer and use it in GitHub Desktop.
Typescript Prevent Default Case
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
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) + "'"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.