Last active
January 23, 2021 19:26
-
-
Save willmtemple/61768b06fa17a27cf33d0daf0c6e8389 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
type DemoEnum = Foo | Bar; | |
interface Foo { | |
kind: "Foo", | |
n: number | |
} | |
interface Bar { | |
kind: "Bar", | |
s: string | |
} | |
const values: DemoEnum[] = [ | |
{ kind: "Foo", n: 10001 }, | |
{ kind: "Bar", s: "Hello world!" } | |
]; | |
for (const value of values) { | |
switch (value.kind) { | |
case "Foo": | |
// TypeScript knows value: A in this block | |
console.log(`Got a Foo with a number: ${value.n}`); | |
break; | |
case "Bar": | |
// and here, value: B | |
console.log(`Got a Bar with a string: ${value.s}`); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment