Skip to content

Instantly share code, notes, and snippets.

@chandu-io
Last active September 21, 2019 14:46
Show Gist options
  • Save chandu-io/0f6f4f1e78440453ab7ef9f7a667d6ea to your computer and use it in GitHub Desktop.
Save chandu-io/0f6f4f1e78440453ab7ef9f7a667d6ea to your computer and use it in GitHub Desktop.
ts :: exhaustive type checking - `Extract`
// Inspired from article
// https://medium.com/@wittydeveloper/typescript-super-types-62ca18810730
type Square = { kind: 'square'; side: number };
type Rectangle = { kind: 'rectangle'; width: number; length: number };
type Circle = { kind: 'circle'; radius: number };
type Shape = Square | Rectangle | Circle;
type ShapeKind = Shape['kind'];
// type AreaList = { [K in Shape['kind']]: (shape: Extract<Shape, { kind: K }>) => number };
type AreaList = { [K in ShapeKind]: (shape: Extract<Shape, { kind: K }>) => number };
const areaCalc: AreaList = {
square: (s: Square) => s.side * s.side,
rectangle: (s: Rectangle) => s.width * s.length,
circle: (s: Circle) => (s.radius * s.radius * 22) / 7
};
// with destructuring
const areaCalc2: AreaList = {
square: ({ side }) => side * side,
rectangle: ({ width, length }) => width * length,
circle: ({ radius }) => (radius * radius * 22) / 7
};
const computedAreas = [
areaCalc['square']({ kind: 'square', side: 10 }),
areaCalc['rectangle']({ kind: 'rectangle', width: 10, length: 10 }),
areaCalc['circle']({ kind: 'circle', radius: 10 }),
areaCalc2['square']({ kind: 'square', side: 10 }),
areaCalc2['rectangle']({ kind: 'rectangle', width: 10, length: 10 }),
areaCalc2['circle']({ kind: 'circle', radius: 10 })
];
console.log(computedAreas);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment