【问题标题】:Typescript: Function with a generic type enforced within generic objects on return?打字稿:返回时在泛型对象中强制执行泛型类型的函数?
【发布时间】:2018-10-22 11:46:20
【问题描述】:

我基本上是在尝试创建一个简单的“GROUP BY”函数,该函数将采用特定类型的数组,并返回一个通用对象,该数组被拆分并以我指定的任何参数为键。换句话说,如果我有一个数组,其中每个元素的类型都是“Customer”,并且我想使用此函数按“Customer.firstName”进行分组,我想向它传递一个数组 Customer[] 并接收一个对象 {string :Customer[]} 作为回报,其中字符串是名字,这样解析器就知道对象的值仍然需要是客户数组。这是我所拥有的:

export class GroupUtil {
/* Take a typed array and returns an object of similarly typed arrays for which the key is the specified parameter. */
public static KeyArrayOn<T>(arr:T[], key:string):{} {
    let res:{} = {};
    for (let i of arr) {
        let k:any = i[key];
        if (res[k]) res[k].push(i); else res[k] = [i];
    }
    return (res);
}

我想做的是输入 this 以返回一个常规对象,其中每个成员都必须是一个仅由传入的通用数组类型组成的数组。这在 TS 中可能吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以将返回类型设置为{[key: string]: T[]}:

    public static KeyArrayOn<T>(arr: T[], key: string): {[key: string]: T[]} {
       ...
    }
    

    demo

    【讨论】:

    • 谢谢,这就是我要找的语法!
    猜你喜欢
    • 2020-06-29
    • 2021-10-04
    • 2020-10-11
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多