utilitypes-ts
    Preparing search index...

    Type Alias GroupBy<T, K>

    GroupBy: {
        [Key in T[K] extends PropertyKey ? T[K] : never]: T extends T
            ? Key extends T[K] ? T : never
            : never
    }

    Groups a type T by the values of a key K.

    Type Parameters

    • T

      The target type (typically a union of objects)

    • K extends KeyOfType<T, PropertyKey>

      The key to group by (must be a key of T with a PropertyKey type)

    type Apple = {
    type: "fruit";
    color: "green";
    };

    type Banana = {
    type: "fruit";
    color: "yellow";
    };

    type Tomato = {
    type: "vegetable";
    color: "red";
    };

    type GroupedByType = GroupBy<Apple | Banana | Tomato, "type">;
    // ^?
    // {
    // fruit: Apple | Banana;
    // vegetable: Tomato;
    // }

    type GroupedByColor = GroupBy<Apple | Banana | Tomato, "color">;
    // ^?
    // {
    // green: Apple;
    // yellow: Banana;
    // red: Tomato;
    // }