Created
December 3, 2022 20:25
-
-
Save adatta02/76f54ff594f8146bc73517c4aab19612 to your computer and use it in GitHub Desktop.
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
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