Skip to content

Instantly share code, notes, and snippets.

@outring
Last active October 26, 2017 09:57
Show Gist options
  • Save outring/9fe354cb6ae32f65c590317a6b59dc18 to your computer and use it in GitHub Desktop.
Save outring/9fe354cb6ae32f65c590317a6b59dc18 to your computer and use it in GitHub Desktop.
TypeScript exhaustive compile-time checks with `never`
//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