Closed
Description
This works, AS EXPECTED:
class Cat {}
class Dog {}
function logType1(animal: Cat|Dog) {
if (animal instanceof Cat) {
console.log("cat");
}
else if (animal instanceof Dog) {
console.log("dog");
}
}
This doesn't work, which is debatable since undefined instanceof Cat
is legal JS but I prefer the type warning since it catches errors:
function logType2(animal: Cat|Dog|void) {
if (animal instanceof Cat) {
console.log("cat");
}
else if (animal instanceof Dog) {
console.log("dog");
}
}
This doesn't work, but I would definitely expect it to:
function logType3(animal: Cat|Dog|void) {
if (typeof animal === "undefined" || animal === null) { // edited to check for null as well, since void can be either
console.log("no animal");
}
else if (animal instanceof Cat) {
console.log("cat");
}
else if (animal instanceof Dog) {
console.log("dog");
}
}
See playground for code.
As it stands, if a union type contains void, I don't know how to use instanceof
with it.