Type Checking with instanceof

This lesson delves further into type checking with instanceof and how TypeScript uses it to compare types.

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 C2 inherits C1. On line 3, an instance of C2 is created but when checked to see if it is C1, it is true. Line 7 also returns true. This peculiarity is in regards to inheritance and instanceof.

Get hands-on with 1400+ tech skills courses.