joshstrike
joshstrike

Reputation: 1823

Typescript: Function with a generic type enforced within generic objects on return?

I'm basically trying to create a simple "GROUP BY" function that will take an array of a specific type, and return a generic object where that array is split up and keyed upon whatever parameter I specify. In other words, if I have an array where every element is type "Customer", and I want to use this function to group by "Customer.firstName", I want to pass it an array Customer[] and receive an object {string:Customer[]} in return where the string is the first name and such that the parser understands that the object's values are still required to be an array of Customers. Here's what I have:

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

What I'd like to do is type this to return a regular object where every member had to be an array composed only of the generic array type that was passed in. Is that possible in TS?

Upvotes: 1

Views: 225

Answers (1)

tony19
tony19

Reputation: 138306

You could set the return type to be {[key: string]: T[]}:

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

demo

Upvotes: 1

Related Questions