Home > Enterprise >  Get type of union member
Get type of union member

Time:11-30

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'"];

CodePudding user response:

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

  • Related