Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class B extends A during runtime

In TypeScript/Javscript, how do I check if class B extends class A

class A {
  ...
}

class B extends A {
  ...
}

assert(B extends A) // How to do something like this?

Answer:

Couple of ways to do this. Thanks to @Daniel and @AviatorX

B.prototype instanceof A        // true
Object.getPrototypeOf(B) === A  // true
Reflect.getPrototypeOf(B) === A // true

Not sure whats the most TypeScript idiomatic way to do it or if there are any missing edge cases but worked for my use case

like image 302
Krimson Avatar asked Nov 06 '22 18:11

Krimson


1 Answers

You can use the instanceof to check if the constructor prototype is an instance of A:

export class A {
}

export class B extends A {
}

console.log(B.prototype instanceof A);

Outputs true for me.

like image 123
Daniel Avatar answered Nov 14 '22 23:11

Daniel