I have a simple question: Is it possible to obtain a type of a part of a union in TypeScript?
For example, you can often use lookup types like this:
interface Person {
name: string;
}
type Name = Person['name']
Now, I'm assuming that it is not possible with unions like this:
type Entity =
{ __type: 'Company', name: string }
| { __type: 'Employee', firstName: string };
So, is there any way how to obtain a part of a union? Something like this:
type Company = DoTheMagic<Entity, { __type: 'Employee' }>
const company: Company = ...;
console.log(company.name) // OK
console.log(company.firstName) // Compile error
We can use the conditional type Extract<T, U>. If T is a union, the result of Extract will be all members of the T union that satisfy the constraint U (aka, T extends U)
type Company = Extract<Entity, { __type: 'Employee' }>
// Same as
type Company = {
__type: "Employee";
firstName: string;
}
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