Skip to content

Instantly share code, notes, and snippets.

@mochki
Last active November 1, 2018 19:20
Show Gist options
  • Save mochki/899a4032e73bfa10ecbfb6000c9b0ccf to your computer and use it in GitHub Desktop.
Save mochki/899a4032e73bfa10ecbfb6000c9b0ccf to your computer and use it in GitHub Desktop.
Exhaustiveness Checking in TypeScript
// This is from Microsoft's presentation
type Shape =
| {kind: 'circle'; radius: number}
| {kind: 'rectangle'; w: number; h: number}
| {kind: 'sqaure'; size: number}
// This function will throw ts-errors if obj ever comes in as something other than error
function assertNever(obj: never) {
throw new Error('Unexpected object')
}
function getArea(shape: Shape) {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2
case 'rectangle':
return shape.w * shape.h
case 'sqaure':
return shape.size ** 2
}
// For example, if one of the cases above was missing, shape would be infered as that type
// which would throw ts error
assertNever(shape)
}
const shape: Shape = {kind: 'circle', radius: 10}
const area = getArea(shape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment