1

When i want to check if a function parameter is a derived class, the instanceof operator allows me to compare it against virtually any class, ignoring the fact that class Random is completely incompatible with other classes.

class Tag {
  public name = '';
}

class TagWithIcon extends Tag {
  public icon = '';
}

class Random {
  public number = 0;
}

function test<Item extends Tag>(item: Item) {
  if(item instanceof Random) {
    console.log('fail')
  }
}

Ideally, the compiler should throw an error when I try to compare my parameter against an incompatible class (i.e. the item instanceof Random condition), but the resulting code produces no errrors from tsc...

Am I doing something wrong?

BMFreed
  • 11
  • 1
  • 3
    This is a known issue and there is a request to allow detecting invalid `instanceof` checks at [#32801](https://github.com/microsoft/TypeScript/issues/32801) but it has been in status "Awaiting More Feedback" for over 3 years. I'll doubt that this is implemented soon. – Tobias S. Feb 03 '23 at 15:01

0 Answers0