How does one use polymorphism instead of instanceof? (And why?)

The main difference between if…else… (or switch, or Visitor), and between polymorphism is modularity. There’s so called open-closed principle, which basically means, that when you add a new feature to an existing program, the less changes you make in existing code the better (because every change requires some work, and may introduce bugs). So let’s … Read more

instanceof Vs getClass( )

The reason that the performance of instanceof and getClass() == … is different is that they are doing different things. instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype. getClass() == … tests whether the types are identical. So … Read more

Why not use instanceof operator in OOP design?

instanceof simply breaks the Open/Close principle. and/or Liskov substitution principle If we are not enough abstract because of instanceof usage, each time a new subclass makes an entrance, the main code gathering the logic of the application might be updated. This is clearly not what we want, since it could potentially break the existing code … Read more

Why does ‘instanceof’ in TypeScript give me the error “‘Foo’ only refers to a type, but is being used as a value here.”?

TL;DR instanceof works with classes, not interfaces nor type aliases. What’s TypeScript trying to tell me? The issue is that instanceof is a construct from JavaScript, and in JavaScript, instanceof expects a value for the right-side operand. Specifically, in x instanceof Foo JavaScript will perform a runtime check to see whether Foo.prototype exists anywhere in … Read more