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

如何在TypeScript中声明含固定属性的嵌套动态对象?

TypeScript 嵌套动态对象的正确声明方式

需要声明的对象结构如下:

{
  foo: "bar",
  dynamicKey_1: {
    innerKey: "bar",
  },
  dynamicKey_2: {
    innerKey: "bar",
  },
}

直接使用包含固定属性和索引签名的接口会触发报错:

interface NestedObject {
  foo: string;
  [key: string]: {
    innerKey: string;
  };
}

错误信息:

Property 'foo' of type 'string' is not assignable to 'string' index type '{ innerKey: string; }'.ts(2411)

错误原因

TypeScript 规定,当接口同时包含固定属性和字符串索引签名时,所有固定属性的类型必须兼容索引签名的类型。这里foo的类型是string,和索引签名要求的{ innerKey: string }类型不匹配,因此触发报错。

解决方案

通过交叉类型将固定属性和索引签名分开声明,让固定属性的类型覆盖索引签名中对应键的类型即可:

type NestedObject = {
  foo: string;
} & {
  [key: string]: { innerKey: string };
};

也可以用Record工具类型简化索引签名部分,效果完全一致:

type NestedObject = {
  foo: string;
} & Record<string, { innerKey: string }>;

这样声明后,既能正确识别固定属性foo的string类型,也能确保其他任意字符串键对应的值都是包含innerKey的对象。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:49:54