How to make a union type from a type alias or interface properties in TypeScript?
How to make a union type from a type alias or interface properties in TypeScript?
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:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.