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

TypeScript中如何从数组类型中排除指定字段

解决方案

你需要先处理数组中单个Foo类型的结构,移除nested里的unwanted字段,再将处理后的类型包装成数组,就能得到目标结构:

type Foo = {
  nested:{
    unwanted:string
    wanted:string
  }
}

type Bar = {
  foos: Foo[]
}

// 先定义排除了unwanted的单个Foo类型
type CleanedFoo = Omit<Foo, 'nested'> & {
  nested: Omit<Foo['nested'], 'unwanted'>
}

// 目标数组类型
type CleanedFooArray = CleanedFoo[]

// 如果要直接从Bar类型推导:
type CleanedFoosFromBar = (Omit<Bar['foos'][number], 'nested'> & {
  nested: Omit<Bar['foos'][number]['nested'], 'unwanted'>
})[]

你之前写的DoesntWork只处理了nested这个叶子节点的类型,没有保留整个Foo的结构并包装成数组。上面的写法先修正单个Foo的结构,再生成数组类型,就能得到符合需求的新结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:01:55