[typescript]advanced type guard

Sat Apr 05

typescript

Author:Noritaka

Astro
class Dog {
  speak() {
    console.log('bow-wow');
  }
}

class Bird {
  speak() {
    console.log('tweet-tweet');
  }
  fly() {
    console.log('flutter');
  }
}

type Pet = Dog | Bird;
function havePet(pet: Pet) {
  pet.speak();
  if (pet instanceof Bird) {
    pet.fly();
  }
}

havePet(new Bird())
havePet(new Dog())
havePet({
  speak() {
    console.log('hello'), console.log('world');
  }
});

// havePet({
//   speak() {
//     console.log('hello'),
//       fly(){
//       console.log('not fly'); //it can't works.
//     }
//   }
// });

typescript