Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to narrow the return type of array.groupBy in typescript?

I wrote this groupBy function:

function groupBy<T>(arr: Array<T>, key: keyof T): Record<any, Array<T>> {
    const result = {} as Record<any, Array<T>>;

    for (const item of arr) {
        const groupKey = item[key];
        if (!result[groupKey]) {
            result[groupKey] = [] as any;
        }
        result[groupKey].push(item);
    }

    return result;
}

And I would like to narrow its return type to Record<U, Array<T>>, how can I do this?
Also, I would like to remove the as any that I added to put a compilation error under the rug.

Here is a typescript playground.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I made it work by defining a type for the key you are grouping by and making sure the object type T has such a key and its value is a type compatible with Record allowed key types:

function groupBy<K extends string, T extends { [key in K]: string | number | symbol }>(arr: Array<T>, key: K): Record<T[K], Array<T>> {
    const result = {} as Record<T[K], Array<T>>;

    for (const item of arr) {
        const groupKey = item[key];
        if (!result[groupKey]) {
            result[groupKey] = [];
        }
        result[groupKey].push(item);
    }

    return result;
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading