如何在运行时检查 class B 是否扩展 A

How to check if a class B extends A during runtime

在 TypeScript/Javscript 中,如何检查 class B 是否扩展 class A

class A {
  ...
}

class B extends A {
  ...
}

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

答案:

有几种方法可以做到这一点。感谢@Daniel 和@AviatorX

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

不确定最 TypeScript 惯用的方法是什么,或者是否有任何遗漏的边缘情况但适用于我的用例

您可以使用 instanceof 来检查构造函数原型是否是 A 的实例:

export class A {
}

export class B extends A {
}

console.log(B.prototype instanceof A);

为我输出 true