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
相关产品推荐
相关产品推荐

