1

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?

1 Answer 1

1

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

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

demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was the syntax I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.