【问题标题】:Typescript generic type parameter constrain to union typeTypescript 泛型类型参数约束为联合类型
【发布时间】:2018-08-04 03:51:18
【问题描述】:

我有一个函数

 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 类似的东西而不诉诸于 我现在在做什么?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    你可以声明:

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

    但是你不能向 TypeScript 证明 o[prop] 是一个数字,你会得到一个 noImplicitAny 错误。假设您在每个调用站点都知道您传递的是 Owners 还是 Banks,您最好传递属性名称,如下所示:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 2016-11-13
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多