Skip to content

Instantly share code, notes, and snippets.

@adatta02
Created December 3, 2022 20:25
Show Gist options
  • Save adatta02/76f54ff594f8146bc73517c4aab19612 to your computer and use it in GitHub Desktop.
Save adatta02/76f54ff594f8146bc73517c4aab19612 to your computer and use it in GitHub Desktop.
type Pet = IDog | ICat | ILizard;
interface IPet {
type: string;
name: string;
}
interface IDog extends IPet {
type: 'dog';
}
interface ICat extends IPet {
type: 'cat';
}
interface ILizard extends IPet {
type: 'lizard';
}
function woof(dog: IDog) {
console.log(`${dog.name} says woof woof`);
}
function meow(cat: ICat) {
console.log(`${cat.name} says meow`);
}
const yourPets: Pet[] = [{type: 'dog', name: 'frodo'}, {type: 'cat', name: 'garfield'}];
for(const pet of yourPets) {
if(pet.type === 'dog') {
woof(pet);
}else if(pet.type === 'cat') {
meow(pet);
}else{
const n: never = pet;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment