ThomasReggi
ThomasReggi

Reputation: 59355

How to remove from union?

Given a union, is it possible to remove a union?

type V = { cat: string } | { dog: string }

type X = Omit<V, 'dog'>

const exampleA: X = { cat: '23456' }
const exampleB: X = { dog: '23456' }

Upvotes: 2

Views: 1186

Answers (1)

jcalz
jcalz

Reputation: 327934

Depending on your use case, you could define ExcludeWithKeys<T, K> like this:

type ExcludeWithKeys<T, K extends PropertyKey> = Exclude<T, Partial<Record<K, any>>>;

or the equivalent

type ExcludeWithKeys<T, K extends PropertyKey> = T extends { [P in K]?: any } ? never : T;

and use it:

type X = ExcludeWithKeys<V, 'dog'>;
// type X = { cat: string }

const exampleA: X = { cat: '23456' }; // okay
const exampleB: X = { dog: '23456' }; // error

I'm assuming that's what you want for the example code. Note that there are likely plenty of edge cases so you should tweak ExcludeWithKeys<T, K> as necessary. Hope that helps; good luck!

Playground link

Upvotes: 3

Related Questions