Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a key from a discriminated union type?

I have a disciminated union

type MyDUnion = { type: "anon"; name: string } | { type: "google"; idToken: string };

I want to access the name key from the discriminative union, from the MyDUnion type directly. Something like this

type Name = MyDUnion['name']

But typescript won't allow that

Property 'name' doesn't exist on type '{ type: "anon"; name: string } | { type: "google"; idToken: string }'

How can I access it?

To be clear, this is not a valid solution:

type MyName = string;
type MyDUnion = { type: "anon"; name: MyName } | { type: "google"; idToken: string };
type Name = MyName; // this line would be in a different file

This is not valid, because then I would have to export both MyName and MyDUnion types to be used elsewhere.

Any ideas?

like image 698
sayandcode Avatar asked Oct 13 '25 00:10

sayandcode


1 Answers

In order to filter union of objects, usually you need to use Extract: The easy way:

type Result = Extract<MyDUnion , {type: "anon"}>

The more robust:

type MyDUnion = { type: "anon"; name: string } | { type: "google"; idToken: string };

type Filter<Union, Type extends Partial<Union>> = Extract<Union, Type>

type Result = Filter<MyDUnion, { type: 'anon' }>
like image 198
captain-yossarian Avatar answered Oct 14 '25 15:10

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!