簡體   English   中英

在基礎組件Angular 4上實例化通用Type T

[英]Instantiate generic Type T on base component Angular 4

我有一個超級組件,它由一些子組件擴展:

 export class BaseComponent<T extends InternalItem> {

    private _internalGradientItems: T[];

    constructor(cdr: ChangeDetectorRef) {

    }

    protected addRow(item: Item) {
        // here I whant to instatiate the type T. 

    }
}

由於某些原因,我需要在基礎組件上實例化T元素。 我沒有找到解決方案。 唯一認為哪個工作是將對象投射到T。

 let iItem = <T>{ gradientItem: item }

但是我不喜歡這種解決方案,不是干凈安全的解決方案。

你對我有目的嗎?

如果T是一個類並且要實例化它,則需要將構造方法傳遞給該類的BaseComponent 您可以使用一個空的構造函數,也可以使用接受從BaseComponent傳入的屬性的構造函數。

export class BaseComponent<T extends InternalItem> {

    private _internalGradientItems: T[];

    constructor(cdr: ChangeDetectorRef,public ctor: new (arg: { gradientItem: Item })=> T) {

    }

    protected addRow(item: Item) {
        new this.ctor({ gradientItem: item });
    }
}

//Usage:

class InternalItem { /* base props */ }
class DerivedInternalItem extends InternalItem { 
    /* props */
    constructor(arg:  { gradientItem: Item }) {
        super()
    }
}

export class DerivedComponent extends BaseComponent<DerivedInternalItem> {
    constructor(cdr: ChangeDetectorRef) {
        super(cdr, DerivedInternalItem)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM