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

如何将含动态数字键的JavaScript对象转为TypeScript接口?

如何将该JavaScript对象表示为动态TypeScript接口?

首先定义单个子对象的接口,描述其固定结构:

interface TileSection {
  id: number;
  type: string;
  subType: string;
  title: string;
  description: string;
  imageUrl: string;
}

如果需要让type和subType的取值更严谨(比如只能是示例中的固定值),可以用字面量类型做限制:

interface TileSection {
  id: number;
  type: "text";
  subType: "tileDynamicSection";
  title: string;
  description: string;
  imageUrl: string;
}

接着定义外层的动态类型,用索引签名适配任意字符串形式的ID键:

type TileSections = {
  [key: string]: TileSection;
};

如果确定外层的键都是数字格式的字符串,还可以用更精确的模板字面量索引:

type TileSections = {
  [key: `${number}`]: TileSection;
};

这样定义的类型既简洁又动态,不会把6000、6001这类具体ID硬编码到接口中,完全匹配你提供的JavaScript对象结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 08:48:21