How to make a union type from a type ali...
How to make a union type from a type ali...
To create a union type from a type alias or interface properties in TypeScript, you can leverage TypeScript's utility types along with mapped types. This approach allows you to dynamically generate a union type based on the properties of an existing type alias or interface. Here's a step-by-step explanation of how to achieve this:
Mapped types allow you to iterate over the keys of an object type and apply a transformation to its properties. To create a union type from the properties of a type alias or interface, you can use the keyof
type operator to get a union of its keys, and then index into the type to get the types of its properties.
Consider the following type alias Person
:
type Person = {
name: string;
age: number;
isStudent: boolean;
};
To create a union type of the property types of Person
(string | number | boolean
), you can use the following approach:
type PersonPropertyTypes = Person[keyof Person];
Similarly, if you have an interface Car
:
interface Car {
make: string;
model: string;
year: number;
}
You can create a union type of the property types of Car
(string | number
) using the same approach:
type CarPropertyTypes = Car[keyof Car];
keyof Person
or keyof Car
generates a union of the keys of the given type ("name" | "age" | "isStudent"
for Person
and "make" | "model" | "year"
for Car
).Person[keyof Person]
or Car[keyof Car]
then indexes into the original type with this union of keys, resulting in a union of the types of those properties.This technique is powerful for creating types that are derived from the properties of existing types, ensuring your type definitions remain DRY (Don't Repeat Yourself) and maintainable.
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào