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?
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?
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.