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

Time:10-13

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.

CodePudding user response:

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

  • Related