Type Checking with instanceof
Explore the use of the instanceof operator in TypeScript for type checking with classes. Understand how it narrows types by checking prototypes and how inheritance affects its behavior. Learn the differences in instanceof functionality before and after TypeScript version 2.7 to better handle errors, arrays, and maps during runtime type verification.
We'll cover the following...
instanceof with classes
instanceof also comes from JavaScript and executes at runtime. Nevertheless, TypeScript can handle the test operator that is looking at the prototype chain to figure out the type of object. Like typeof, if the comparison with instanceof is positive, the type is narrowed down to the checked type. Instanceof cannot be used for interface checks and is limited to a class comparison since it relies on the constructor function.
The following example shows that ...