You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中对数组类型使用经典Oomit功能?

解决方案

你可以自定义一个专门作用于数组类型的工具类型,直接对数组的元素类型执行Omit操作后重新包装成数组:

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

type Cars = Car[]

// 自定义数组版Oomit工具类型
type OmitFromArray<T extends readonly any[], K extends keyof T[number]> = Array<Omit<T[number], K>>

// 直接作用于Cars数组类型
type Voitures = OmitFromArray<Cars, 'c'>

这个OmitFromArray的逻辑很直白:

  • 通过T[number]提取数组T的元素类型
  • 对元素类型执行Omit<T[number], K>移除指定属性
  • 最后把处理后的元素类型重新包装成数组

如果需要同时兼容对象和数组的场景,也可以写一个带条件分支的通用类型:

type OmitGeneric<T, K extends keyof any> = 
  T extends readonly any[] 
    ? Array<Omit<T[number], K>> 
    : Omit<T, K>

// 既可以处理对象也可以处理数组
type Voiture = OmitGeneric<Car, 'c'>
type Voitures = OmitGeneric<Cars, 'c'>

这样不管传入的是对象类型还是数组类型,都能正确返回移除指定属性后的类型,完全满足你的代码约束要求。

内容的提问来源于stack exchange,提问作者axel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:23:15