如何使用应用于数组类型而不是打字稿中的类型的经典省略功能?

How can I use the classic Omit functionality applied to an array type instead of a type in typescript?

提问人:axel 提问时间:11/15/2023 更新时间:11/15/2023 访问量:28

问:

如何使用应用于数组类型而不是类型的经典 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'>[]

有没有解决方案?

谢谢

数组 泛型 打字稿-实用程序

评论


答:

2赞 Behemoth 11/15/2023 #1

您可以使用索引访问类型从中提取,然后像往常一样使用 Omit,最后将其转换回数组。CarCar[]

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 游乐场

1赞 Harrison 11/15/2023 #2

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

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

你基本上在做什么

type Voiture = Omit<Car, 'c'>

type Voitures = Voiture[]