Skip to content

Instantly share code, notes, and snippets.

@TheCubicleBuddha
Last active April 19, 2019 15:16
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 TheCubicleBuddha/7a8854f244697b9894e41d44e1fc6967 to your computer and use it in GitHub Desktop.
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.
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