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

如何在TypeScript映射类型ValidateResult中新增属性

解决方案

你可以通过两种方式实现需求:

方法一:类型交集(&)

利用TypeScript的类型交集特性,将原映射类型与包含newKey的对象类型合并:

type FieldKey = 'internal' | 'external'

export type ValidateResult = {
  [x in FieldKey]: any
} & {
  newKey: any
}

方法二:扩展映射的联合类型

直接在映射签名中把newKey加入联合类型(无需修改原FieldKey):

type FieldKey = 'internal' | 'external'

export type ValidateResult = {
  [x in FieldKey | 'newKey']: any
}

原写法报错原因

TypeScript语法规则不允许在同一个对象类型字面量中同时存在映射签名([x in FieldKey]: any)和显式属性定义(newKey: any),因此直接添加会触发语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:15:53