The limitations of instanceof

Similar to typeof, there is in JavaScript the instanceof operator. The limitation of instanceof is that it can be only used on a type with a prototype chain: a class. Like typeof, instanceof works at design and runtime and is native to JavaScript:

class MyClass1 {
member1: string = "default";
member2: number = 123;
}
class MyClass2 {
member1: string = "default";
member2: number = 123;
}
const a = new MyClass1();
const b = new MyClass2();
if (a instanceof MyClass1) {
console.log("a === MyClass1");
}
if (b instanceof MyClass2) {
console.log("b === MyClass2");
}

Contrary to typeof, the result of instanceof is not a string and cannot be used in the console.log function; it is possible to set the value in a type or in a variable. It can only be used for comparison purposes. The next example does not compile:

type MyType = instanceOf MyClass1;

The instanceOf limitations are beyond just being focused on class. The instanceOf operator also does not distinguish which class is exactly used in the situation of inheritance. In the next code example, the variable  c is of type MyClass3, which inherits MyClass2.  InstanceOf identifies the variable to be of both types. In the following code, both if are entered:

class MyClass3 extends MyClass2 {
member3: boolean = true;
}
const c = new MyClass3();
if (c instanceof MyClass2) {
console.log("c === MyClass2");
}
if (c instanceof MyClass3) {
console.log("c === MyClass3");
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.96.155