Skip to content

Instantly share code, notes, and snippets.

@ChuckJonas
Last active November 30, 2017 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChuckJonas/ed3bc18e0caee3d3af5734edd8f17ce1 to your computer and use it in GitHub Desktop.
Save ChuckJonas/ed3bc18e0caee3d3af5734edd8f17ce1 to your computer and use it in GitHub Desktop.
Typescript Discriminated Union Example
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