Skip to content

Instantly share code, notes, and snippets.

@nblagoev
Created August 20, 2017 06:56
Show Gist options
  • Save nblagoev/0d7ecb70d090f51dff531ad840f63d69 to your computer and use it in GitHub Desktop.
Save nblagoev/0d7ecb70d090f51dff531ad840f63d69 to your computer and use it in GitHub Desktop.
TypeScript snippets
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;
case "square":
return shape.size ** 2;
}
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