To make a union type from a type alias or interface properties, you can use the indexed access type
syntax and then write the property names to make the union type separated by the union operator symbol (|
) in TypeScript.
TL;DR
// a simple interface
interface Car {
name: string;
yearMade: number;
}
// make a union type from the `name` and
// `yearMade` properties from the `Car` interface
type NameOrYear = Car["name" | "yearMade"]; // NameOrYear -> string | number
For example, let's say we have an interface called Car
having a property called name
with the type of string
and another property called yearMade
having the type of number
like this,
// a simple interface
interface Car {
name: string;
yearMade: number;
}
Suppose we want to make a union type from the name
and yearMade
properties from the Car
interface.
To do that we can make use of the indexed access type
syntax and then write out the property names to make the union type separated by the union operator symbol (|
).
It can be done leik this,
// a simple interface
interface Car {
name: string;
yearMade: number;
}
// make a union type from the `name` and
// `yearMade` properties from the `Car` interface
type NameOrYear = Car["name" | "yearMade"]; // NameOrYear -> string | number
Now if you hover over the NameOrYear
type, you can see that it is a union type composed of string
and number
type which are the same types of the name
and yearMade
properties from the Car
interface.
We have successfully made a union type from interface properties in TypeScript. Yay 🥳!
This method is the same for any type alias
type in TypeScript.
See the above code live in codesandbox.
That's all 😃!