-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Labels
BugA bug in TypeScriptA bug in TypeScriptDuplicateAn existing issue was already createdAn existing issue was already createdFixedA PR has been merged for this issueA PR has been merged for this issue
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.
Metadata
Metadata
Assignees
Labels
BugA bug in TypeScriptA bug in TypeScriptDuplicateAn existing issue was already createdAn existing issue was already createdFixedA PR has been merged for this issueA PR has been merged for this issue