200.Land

overriding-hasinstance.ts

The JavaScript code explores JavaScript's instanceof operator and the [Symbol.hasInstance] method. It defines three classes (A, B, and MyClass) and an array of objects. It customizes the behavior of instanceof for MyClass using [Symbol.hasInstance] to include objects matching certain criteria. Finally, it filters an array using this customized instanceof check, demonstrating polymorphic behavior based on dynamic type checking.

class A {}
class B extends A {}

console.log(new B() instanceof A);

console.log(A[Symbol.hasInstance](new B()));

class MyClass {
  public type = "someType";
  public id = "uniqueInGalaxy";
  public name = "john";
  public static [Symbol.hasInstance](instance: any): boolean {
    return (
      instance.constructor.name === MyClass.name || instance.type === "someType"
    );
  }
}

const data = [
  new MyClass(),
  { type: "someType", id: "uniqueInGalaxy2", name: "james" },
  { type: "someOtherType", id: "uniqueInGalaxy3", name: "james" }
];

console.log(data.filter(datum => datum instanceof MyClass));