Skip to content

Instantly share code, notes, and snippets.

@willmtemple
Last active January 23, 2021 19:26
Show Gist options
  • Save willmtemple/61768b06fa17a27cf33d0daf0c6e8389 to your computer and use it in GitHub Desktop.
Save willmtemple/61768b06fa17a27cf33d0daf0c6e8389 to your computer and use it in GitHub Desktop.
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