Last active
April 19, 2019 15:16
-
-
Save TheCubicleBuddha/7a8854f244697b9894e41d44e1fc6967 to your computer and use it in GitHub Desktop.
This shows how to use "Defensive Programming" (and specifically the "exhaustive type checking" features of TypeScript) to make sure that all code handles all future possibilities.
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
type ITrafficLight = "red" | "redBlinking" | "green" | "yellow" | "yellowBlinking"; | |
function respondToTrafficSignal(signal: ITrafficLight): "stop" | "go" | "pause" { | |
if(signal === "red"){ | |
return "stop"; | |
} else if(signal === "yellow"){ | |
return "pause"; | |
} else if(signal === "green") { | |
return "go"; | |
} else { | |
return neverGonnaGetHere(signal) // The compiler catches the logical error: Type '"redBlinking"' is not assignable to type 'never'. | |
} | |
} | |
function neverGonnaGetHere(hopefullyNotPossibleValue: never): never { | |
throw new Error(`Did not expect this value: ${hopefullyNotPossibleValue}`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment