[typescript]advanced type guard

Sat Apr 05

typescript

Author:Noritaka

Astro
class MyDog {
  speak() {
    console.log('bow-wow')
  }
}
class MyBird {
  speak() {
    console.log('tweet-tweet')
  }
  fly() {
    console.log('flutter');
  }
}

type MyPet = MyDog | MyBird;
function havingPet(pet: MyPet) {
  pet.speak();
  if ('fly' in pet) {
    pet.fly();
  }
  if (pet instanceof MyBird) {
    pet.fly();
  }
}
havingPet({ speak() { console.log('hello') }, fly() { console.log('not fly') } });

typescript