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?
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' }>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With