Created
January 14, 2020 22:43
-
-
Save ksaldana1/1063c636cee697d43ad7f1e8cf9a153d to your computer and use it in GitHub Desktop.
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