Skip to content

instanceof should not exclude possible structural type #17344

Closed
@kube

Description

@kube

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions