Last active
November 30, 2017 23:49
-
-
Save ChuckJonas/ed3bc18e0caee3d3af5734edd8f17ce1 to your computer and use it in GitHub Desktop.
Typescript Discriminated Union Example
This file contains 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
enum CreatureKind { | |
Dog = "Dog", | |
Wolf = "Wulf", | |
Cat = "Cat", | |
Tiger = "Tiger", | |
} | |
interface Barker { | |
bark: () => string; | |
} | |
interface Meower { | |
meow: () => string; | |
} | |
interface Domesticated { | |
play: () => string; | |
} | |
interface Wild { | |
kill: () => string; | |
} | |
type Wolf = Barker & Wild & { kind: CreatureKind.Wolf }; | |
type Dog = Barker & Domesticated & { kind: CreatureKind.Dog }; | |
type Cat = Meower & Domesticated & { kind: CreatureKind.Cat }; | |
type Tiger = Meower & Wild & { kind: CreatureKind.Tiger }; | |
type Canine = Wolf | Dog; | |
type Feline = Cat | Tiger; | |
type Creature = Canine | Feline; | |
const doCreatureStuff = (creature: Creature) => { | |
creature.kind === CreatureKind.Dog || creature.kind === CreatureKind.Wolf ? | |
alert(creature.bark()) : | |
alert(creature.meow()); | |
creature.kind === CreatureKind.Dog || creature.kind === CreatureKind.Cat ? | |
alert(creature.play()) : | |
alert(creature.kill()); | |
}; | |
const fido: Canine = { | |
kind: CreatureKind.Dog, | |
bark: () => "wooof", | |
play: () => "with ball" | |
}; | |
const garfield: Feline = { | |
kind: CreatureKind.Cat, | |
meow: () => "meow", | |
play: () => "with box" | |
}; | |
const balto: Canine = { | |
kind: CreatureKind.Wolf, | |
bark: () => "grrrr", | |
kill: () => "eat chicken" | |
}; | |
const shereKhan: Feline = { | |
kind: CreatureKind.Tiger, | |
meow: () => "rarrr", | |
kill: () => "eat human" | |
}; | |
doCreatureStuff(balto); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment