簡體   English   中英

Typescript通用類型參數限制為聯合類型

[英]Typescript generic type parameter constrain to union type

我有一個功能

 uniqueIds(first: any[], second: any[]): number[] {
        let prop = first[0] instanceof Owner ? "OwnerId"
            : "BankId";
        return _.unique(
            _.map(
                first,
                o => o[prop]
            )
            .concat(
                _.map(
                    second,
                    o => o[prop]
                )
            )
        ).filter(o => o);
    }

銀行或所有者是我希望此功能采用的可能類型,別無其他。 銀行和所有者不共享任何接口或繼承鏈
根據傳入的類型,我想根據函數內第一行所示的屬性索引到對象。

我看上去很丑陋,有沒有辦法去到uniqueIds<T> where T Bank | Owner uniqueIds<T> where T Bank | Owner這樣的東西,而不求助於我目前正在做的事情?

您可以聲明:

function uniqueIds<T extends Owner[] | Bank[]>(first: T, second: T) { ... }

但是您將無法向TypeScript證明o[prop]是一個數字,並且會出現noImplicitAny錯誤。 假設您在每個呼叫站點都知道要傳遞所有者還是銀行,那么最好傳遞屬性名稱,如下所示:

function uniqueIds<K extends string, T extends {[P in K]: number}>(
    prop: K, first: T[], second: T[]): number[] {
    return _.unique(
        _.map(
            first,
            o => o[prop]
        )
        .concat(
            _.map(
                second,
                o => o[prop]
            )
        )
    ).filter(o => o);
}

暫無
暫無

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

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