Typescript's instanceof ignores initial type

53 views Asked by At

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?

0

There are 0 answers