如何将经典的Omit功能应用于数组类型而不是typescript中的类型?

tv6aics1  于 7个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(82)

如何将经典的Omit功能应用于数组类型而不是类型?
例如,我有以下类型

type Car = {
  a: number,
  b: string,
  c: Record<string, unknown> | null
}

type Cars = Car[]

字符串
我想创建没有c: Record<string, unknown> | null的类似类型。
例如,我可以声明。

type Voiture = Omit<Car, 'c'>

type Voitures = Omit<Cars, 'c'>  // obviously not working


对于代码约束,我不能使用Omit<Car, 'c'>[]
有没有解决办法?
谢谢

erhoui1w

erhoui1w1#

您可以使用Indexed Access TypeCar[]中提取Car,然后像往常一样使用Omit,最后将其转换回数组。

type Car = {
  a: number,
  b: string,
  c: Record<string, unknown> | null
}

type Cars = Car[];

type Voitures = Omit<Cars[number], "c">[]
//   ^? type Voitures = Omit<Car, "c">[]

字符串
TypeScript Playground

7uzetpgm

7uzetpgm2#

因此,在这种情况下,我认为您必须执行以下操作:

type Voitures = Omit<Cars[number], 'c'>[]

字符串
你基本上是在做

type Voiture = Omit<Car, 'c'>

type Voitures = Voiture[]

相关问题