Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created October 15, 2022 14:41
Show Gist options
  • Save semlinker/a1576d0c3c4f2ac2f04f983bbcddbaae to your computer and use it in GitHub Desktop.
Save semlinker/a1576d0c3c4f2ac2f04f983bbcddbaae to your computer and use it in GitHub Desktop.
Exhaustive Type Checking with TypeScript
function area(s: Shape) {
switch (s.kind) {
case "square":
return s.size * s.size;
case "rectangle":
return s.width * s.height;
case "circle":
return Math.PI * s.radius * s.radius;
default:
return assertExhaustive(s, 'Reached unexpected case')
}
}
function assertExhaustive(
value: never,
message: string
): never {
throw new Error(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment