Làm thế nào để tạo một kiểu ‘union’ từ một bí danh kiểu hoặc thuộc tính interface trong TypeScript?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
127 lượt xem
Typescript master

Để tạo kiểu union từ bí danh kiểu (type alias) hoặc thuộc tính interface:

  • Bạn có thể sử dụng cú pháp indexed access type.
  • Sau đó viết tên thuộc tính để làm cho kiểu union được phân tách bằng ký hiệu toán tử union (|) trong TypeScript.
// 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
{{login.error}}