Created
March 13, 2020 01:14
-
-
Save ksaldana1/a07ae3b225ee8ffc85b26c181707b3b9 to your computer and use it in GitHub Desktop.
example_1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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