0

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.

3
  • 1
    I don't think your expected result is what you actually expect... some parenthesis would help.
    – Gerrit0
    Commented Sep 30, 2020 at 0:58
  • 1
    Could you parenthesize your type x? It evaluates to type x = Record<"cat", string> | Record<"dog", string> in the IDE; not sure if that's what you really want.
    – jcalz
    Commented Sep 30, 2020 at 1:06
  • @Gerrit0 I updated the post with some parenthesis. Commented Sep 30, 2020 at 3:53

1 Answer 1

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.