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

TypeScript:含例外的索引签名数组定义为何报错?

TypeScript类型报错原因解析

错误代码示例

❌ let b:({[key:string]:string} & {test:number})[] = [{yes:"yes", test:3}]; 

翻译后的报错信息

类型“{ yes: string; test: number; }”无法分配给类型“{ [key: string]: string; } & { test: number; }”。
类型“{ yes: string; test: number; }”无法分配给类型“{ [key: string]: string; }”。
属性“test”与索引签名不兼容。
类型“number”无法分配给类型“string”。ts(2322)

报错原因

问题根源在于你定义的交叉类型存在逻辑冲突:

  • {[key:string]:string}是全局约束,要求所有字符串类型的键,对应的值必须是string类型。
  • 交叉类型& {test:number}要求存在test键且值为number,但test本身属于字符串类型的键,直接违反了前面索引签名的全局约束。
  • TypeScript会严格校验交叉类型的所有规则,不会因为单独声明了某个属性就忽略索引签名的要求——它要求所有属性(包括明确声明的test)都必须符合索引签名的类型规定,因此出现了类型不兼容的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:42:23