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