Skip to content

Instantly share code, notes, and snippets.

@oneillci
Created May 23, 2017 06:25
Show Gist options
  • Save oneillci/99c5561d01f39b389e37730d726df5b9 to your computer and use it in GitHub Desktop.
Save oneillci/99c5561d01f39b389e37730d726df5b9 to your computer and use it in GitHub Desktop.
type Shape =
{ kind: "circle", radius: number} |
{ kind: "rectangle", w: number, h: number} |
{ kind: "square", size: number}
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; // commenting this leads to compiler error!! :)
case "square": return shape.size ** 2;
}
assertNever(shape);
}
const shape: Shape = {kind: "circle", radius: 0};
const area = getArea(shape);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment