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

TypeScript中如何正确声明键为字符串、值为对象数组的对象类型?

TypeScript类型声明实现

首先拆分结构分层定义类型,可读性更高,也方便后续复用:

// 定义数组成员的基础类型
interface ColorItem {
  title: string;
  summary: string;
  link: string;
  // 可选属性添加?标记
  image?: string;
}

// 定义外层对象类型:键为任意字符串,值为ColorItem类型的数组
// 也可以写成 { [key: string]: ColorItem[] },和Record写法效果一致
type ColorMap = Record<string, ColorItem[]>;

// 变量声明时绑定类型
let colors: ColorMap = {
  "blue" : [
    {
      title: "blue",
      summary : "blue is ...",
      image : "image of blue", // 可选属性可以省略
      link : "https:// ..."
    }, 
    {
      title: "blue",
      summary : "blue is ...",
      link : "https:// ..."
    }
  ], 
  "yellow" : [
    {
      title: "yellow",
      summary: "yellow is ...",
      link: "https://..."
    }
  ]
}

如果不需要复用相关类型,也可以直接内联写类型定义:

let colors: Record<string, {
  title: string;
  summary: string;
  link: string;
  image?: string;
}> = {
  // 赋值逻辑和上面一致
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:00:06