Last active
October 26, 2017 09:57
-
-
Save outring/9fe354cb6ae32f65c590317a6b59dc18 to your computer and use it in GitHub Desktop.
TypeScript exhaustive compile-time checks with `never`
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
//Play with it here: https://goo.gl/dH6DLj | |
class UnexpectedValueError { | |
public readonly stack: string | undefined; | |
public readonly message: string; | |
constructor(value: never) { | |
const error = new Error(`Unexpected value ${value}`); | |
this.stack = error.stack; | |
this.message = error.message; | |
} | |
} | |
class Type1 { | |
} | |
class Type2 { | |
} | |
class Type3 { | |
} | |
//If `Type3` is added here code won't typecheck until instanceof check is added to `getClassTypeLabel` | |
type Type = Type1 | Type2; | |
function getClassTypeLabel(instance: Type): string { | |
if (instance instanceof Type1) { | |
return "Type 1"; | |
} | |
if (instance instanceof Type2) { | |
return "Type 2"; | |
} | |
throw new UnexpectedValueError(instance); | |
} | |
//If `"type3"` is added here code won't typecheck until new case is added to `getValueTypeLabel` | |
type ValueType = "type1" | "type2"; | |
function getValueTypeLabel(value: ValueType): string { | |
switch (value) { | |
case "type1": | |
return "Type 1"; | |
case "type2": | |
return "Type 2"; | |
default: | |
throw new UnexpectedValueError(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment