Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get type of union member

Is there any way to get a specific member of a union type based on a key in the union without explicitly defining each member of the union?

type Thing = {
  type: "person",
  data: {
    name: "John"
  }
} | {
  type: "building",
  data: {
    address: "111 Main Street"
  }
}

type Person = Thing["where 'type' = 'person'"];

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can accomplish narrowing down via Distributive Conditional Types:

When conditional types act on a generic type, they become distributive when given a union type.

Then we use the fact that the union of type T and never is the same as T

type NarrowUnion<T, N> = T extends { type: N } ? T : never;
type Person = NarrowUnion<Thing, 'person'>

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading