2017-09-21 64 views
1

在Angular/TypeScript中,如何在运行时检查由Type<T>表示的类型是否扩展了某些特定的类BaseClass检查类型<T>是否扩展了特定的类

例如,假设我们使用ApplicationRef.componentTypes来获得Type<any>[]。现在,我们希望通过它来迭代,并检查是否当前Type<any>延长一些BaseClass

const types: Type<any>[] = this.applicationRef.componentTypes; 

this.navigationComponents = types.filter((type: Type<any>) => { 
    // Here we need check whether type extends BaseClass 
}); 

应该是什么在支票上面的代码?

回答

1

因为这样原型继承的作品,你可以使用prototypeinstanceof,以确定它是否延长BaseClass

types.filter((type: Type<any>) => type.prototype instanceof BaseClass); 
+0

好的,谢谢!如果我没有弄错,只有当'BaseClass'是一个类,并且如果它是一个接口,它才会工作?没有办法使它与接口一起工作。 –

+0

是的,它必须是一个类,但只有构造函数可以被分配到'类型'。无论如何,接口根本不存在于运行时,因为类型系统被擦除。 – cartant

相关问题