Home > Enterprise >  Using Typscript how can a create a union of filtered String literal types from an object
Using Typscript how can a create a union of filtered String literal types from an object

Time:08-07

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 (e.g. "WHITE") and create a type:

"tesla" | "rivian"

CodePudding user response:

You can filter with intersection type.

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

More general solution would be using Extract/Exclude utility types.

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

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