Closed
Description
TypeScript Version: 2.4.2
I was playing with TypeScript, and faced this issue, where I can pass a structural type as an object nominally typed.
But using instanceof
as a type guard makes TypeScript believe it could not be an Animal anymore.
Code
class Animal {
run() { }
}
// Create a nominally-typed animal
const a = new Animal()
// Create a structurally-typed animal
const b: Animal = {
run() { }
}
function makeAnimalRun(animal: Animal | string) {
if (animal instanceof Animal) {
// Here animal is inferred as an Animal, which is true
animal.run()
}
else {
// Here animal is inferred as a string, but still COULD BE of structural type Animal
console.log(`${animal.toUpperCase()}!!!!`)
}
}
makeAnimalRun(a)
makeAnimalRun(b) // Why is this accepted?
So instanceof
should not work as a type guard anymore (or at least not remove the type as a possibility from the other block), or structural typing should not be permitted with nominal types.