Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript lookup/conditional types and unions

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
like image 239
Deftomat Avatar asked Jan 21 '26 14:01

Deftomat


1 Answers

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;
}
like image 143
Titian Cernicova-Dragomir Avatar answered Jan 23 '26 08:01

Titian Cernicova-Dragomir



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!