How to get union of key values, and preserve union values

74 views Asked by At

I have a type that looks like this:

type g = {
    cat: (Record<"cat", string> | undefined);
    dog: ({ dogSound: string } | Record<"dog", string>);
}

type f = g[keyof g]

I'd like to create a union, and get this result:

type x = (Record<"cat", string> | undefined) & ({ dogSound: string } | Record<"dog", string>)

Essentially I want to get the values:

When I do

type g = {
    cat: (Record<"cat", string> | undefined);
    dog: ({ dogSound: string } | Record<"dog", string>);
}

type f = g[keyof g]

It produces this:

type f = Record<"cat", string> | {
    dogSound: string;
} | Record<"dog", string> | undefined

It becomes one big union, and it's not segregated anymore, there are no parenthesis.

1

There are 1 answers

0
ThomasReggi On

I think that this achieves what I want:

type UnionToIntersectionValues<U, K extends keyof U = keyof U> =
    (K extends never
        ? unknown
        : K extends unknown
        ? (k: U[K]) => void
        : never
    ) extends (k: infer I) => void ? I : never