簡體   English   中英

如何在TypeScript中按通用類型過濾類型列表?

[英]How to filter a list of types by a generic type in TypeScript?

我需要一個函數,該函數從候選列表中返回給定類型的所有實例,所有這些實例均來自公共超類。

例如,我可以寫:

class A {
    protected children: A[] = [];

    getChildrenOfType<T extends A>(): T[] {
        let result: T[] = [];
        for (let child of this.children) {
            if (child instanceof T)
                result.push(<T>child);
        }

        return result;
    }
}

與例如

class B: extends A {}
class C: extends B {}
class D: extends A {}

等等

但是,這不能編譯。 child instanceof T給我“ T僅表示類型,但在此處用作值”。 但是,任何具體的類(例如C)都在那里工作。 顯然,這是引起問題的通用類型。 在這種情況下使用的正確構造是什么? 實施這種通用過濾還需要其他條件嗎?

您可以使用此代碼。

class A {
    protected children: A[] = [];

    getChildrenOfType<T extends A>(t: new (...args: any[]) => T): T[] {
        let result: T[] = [];
        for (let child of this.children) {
            if (child instanceof t)
                result.push(<T>child);
        }

        return result;
    }
}

instanceof的右側需要是一個構造函數,例如new() => MyClass 您可以將其作為方法的參數。

可以像這樣使用getChildrenOfType方法:

var a = new A();
// push some childs to a.children
a.getChildrenOfType(B)

在操場上檢查一下

暫無
暫無

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

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