Home > OS >  Type of supplied parameter when type is an intersection of two classes?
Type of supplied parameter when type is an intersection of two classes?

Time:08-24

Suppose I have code that looks basically like this:

class dog {
    bark() { console.log("bark")}
    get legs() : number {return 4}
    get toy() : string {return "ball"}
}
class cat {
    meow() { console.log("meow")}
    get legs() : number {return 4}
    get likesCatnip() : boolean {return true}
}

let pet : cat | dog;
let ricky = new cat();

function makeNoise( pet : cat | dog) {
    if ([isDog]) (
        pet.bark()
    ) else {
        pet.meow()
    }
}

What is the 'correct' way to tell if the "pet" parameter is a cat or a dog in makeNoise()? I know I could use pet.constructor.name for isDog -- but that seems a bit hacky way to tell if pet instanceOf Cat. Like for example, if somebody were to define a class StBernard extends dog, I would run into trouble.

CodePudding user response:

class Animal {}
class Rabbit extends Animal {}

let rabbit = new Rabbit();
alert(rabbit instanceof Animal); // true

instanceof works for inherited class too.

 if (pet instanceof dog) (
        pet.bark()
    ) else {
        pet.meow()
    }

CodePudding user response:

You can narrow it down using type predicates. It's going to be like the following:

function isDog(pet: any): pet is dog {
  return pet instanceof dog; // Or something else that tells the object is a dog
}

function makeNoise( pet : cat | dog) {
  if (isDog(pet)) {
      pet.bark();
  } else {
      pet.meow();
  }
}
  • Related