Câu hỏi phỏng vấn Typescript
Câu hỏi

How to make a union type from a type ali...

Câu trả lời

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:

Using Mapped Types to Extract Property Types

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.

Example with a Type Alias

Consider the following type alias Person:

typescript Copy
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:

typescript Copy
type PersonPropertyTypes = Person[keyof Person];

Example with an Interface

Similarly, if you have an interface Car:

typescript Copy
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:

typescript Copy
type CarPropertyTypes = Car[keyof Car];

Detailed Explanation

  • 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.

References

  • The concept of creating a union type from the properties of a type alias or interface is based on TypeScript's...
expert

expert

Gợi ý câu hỏi phỏng vấn

junior

How could you check null and undefined in TypeScript?

entry

Explain generics in TypeScript

junior

What does the pipe, | mean in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào