简体   繁体   English

使用 Typscript 如何从 object 创建过滤字符串文字类型的联合

[英]Using Typscript how can a create a union of filtered String literal types from an object

In the following example:在以下示例中:

const cars = [
    {brand: "tesla", model:"Y", colour: "BLACK"},
    {brand: "tesla", model: "S", colour: "WHITE"},
    {brand: "hyundai", model: "Ioniq5", colour: "BLACK"},
    {brand: "hyundai", model: "Ioniq6", colour: "BLACK"},
    {brand: "rivian", model: "R1", colour: "WHITE"}
] as const

using the following:使用以下内容:

type Brands = (typeof cars)[number]["brand"]

creates a type:创建一个类型:

"tesla" | “特斯拉” | "hyundai" | “现代” | "rivian" “里维安”

Is it possible to create a union type that filters const cars, based on the colour (eg "WHITE") and create a type:是否可以根据颜色(例如“WHITE”)创建一个过滤常量汽车的联合类型并创建一个类型:

"tesla" | “特斯拉” | "rivian" “里维安”

You can filter with intersection type.您可以使用交叉点类型进行过滤。

type Brands = ((typeof cars)[number] & { colour: "WHITE" })["brand"]

More general solution would be using Extract/Exclude utility types.更通用的解决方案是使用Extract/Exclude实用程序类型。

type Extract<T, U> = T extends U ? T : never

type Brands = Extract<(typeof data)[number], { colour: "WHITE" }>["brand"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM