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

How to get a union type from a property value in an object of objects?

Let’s say I have an object:

const familyCars = {
  father: {
    make: "BMW",
    color: "white"
  },
  mother: {
    make "Toyota",
    color: "white"
  },
  son: {
    make: "Ford",
    color: "black"
  }
}

How to define a union type that will include all possible values of mark property for all family members: "BMW" | "Toyota" | "Ford"

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

>Solution :

You can achieve this with indexed access types but it will also require to define your const with as const to prevent the values to be widen to string.

const familyCars = {
  father: {
    make: "BMW",
    color: "white"
  },
  mother: {
    make: "Toyota",
    color: "white"
  },
  son: {
    make: "Ford",
    color: "black"
  }
} as const

type FamilyCar = typeof familyCars;

type Maker = FamilyCar[keyof FamilyCar]['make']

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