2

I have a union type like:

type T = {} | ({ some: number } & { any: string })

Then how can I narrow this type to the latter? Of course this didn't work:

type WithEntries = Exclude<T, {}>

resulting in never.

Is this possible?

yuhr
  • 141
  • 1
  • 9

1 Answers1

3

Here you go

type T = {} | ({ some: number } & { any: string })

type X<T> = T extends {} ? ({} extends T ? never : T) : never;

type WithEntries = X<T>; //  { some: number; } & { any: string; }

The first condition 'distributes' parts of the union type, so that the second condition can 'filter out' empty type by converting it to never, the result is union of never | (non-empty parts of T), and union never | P is just P for any P.

The idea comes from this answer.

artem
  • 46,476
  • 8
  • 74
  • 78