Skip to content

Instantly share code, notes, and snippets.

@ksaldana1
Created March 13, 2020 01:14
Show Gist options
  • Save ksaldana1/a07ae3b225ee8ffc85b26c181707b3b9 to your computer and use it in GitHub Desktop.
Save ksaldana1/a07ae3b225ee8ffc85b26c181707b3b9 to your computer and use it in GitHub Desktop.
example_1
// 1) Types that have a common, singleton type property — the discriminant.
// In this example the "kind" property is the discriminant.
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
// 2) A type alias that takes the union of those types — the union.
type Shape = Square | Rectangle | Circle;
function area(s: Shape) {
// 3) Type guards on the common property.
// A switch statement acts as a "type guard" on
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment