2017-09-21 101 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

相關問題