How to make union type from all the properties in a type alias or an interface in TypeScript?

January 23, 2022 - 2 min read

To make a union type from all the properties in a type alias or an interface type, we can use the indexed access type syntax, and then we can use the keyof type operator followed by the name of the interface or type alias in TypeScript.

TL;DR

// a simple interface
interface Car {
  name: string;
  yearMade: number;
  isSuv: boolean;
}

// make union type from all the
// properties from the `Car` interface
type CarProps = Car[keyof Car]; // CarProps -> string | number | boolean

For example, let's say we have an interface called Car with a property called name having the type of string, another property called yearMade having the type of number, and another property called isSuv having the type of boolean like this,

// a simple interface
interface Car {
  name: string;
  yearMade: number;
  isSuv: boolean;
}

Suppose we want to make a union type from all the properties in the Car interface.

To do that we can use the indexed access type syntax and then use the keyof type operator followed by the name of the interface we need to make the union type from. In our case, it is the Car interface.

It can be done like this,

// a simple interface
interface Car {
  name: string;
  yearMade: number;
  isSuv: boolean;
}

// make union type from all the
// properties from the `Car` interface
type CarProps = Car[keyof Car]; // CarProps -> string | number | boolean

Now if you hover over the CarProps type, you can see that it is now a union type composed of string, number, and boolean type which is the same as the types of the properties in the Car interface.

We have successfully made union type from all the properties in the interface. Yay 🥳!

This method can be used for the type alias type in TypeScript.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.