首页 > 解决方案 > 打字稿声明地图类型

问题描述

我正在使用打字稿,我需要定义一种类型来描述这种数据格式:

{
  "apple": [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}],
  "banana":[{"color": "yellow","taste": "okay"}]
}

这就是我现在所拥有的,我声明了一个 Fruit 类型并使用 Record 将其制作为一个映射,然后我添加了字符串作为键(这将是水果名称,如苹果、香蕉)并将一个类型/接口FruitDescription类声明为 Fruit 的值.

type Fruit = Record<string, FruitDescription>

interface FruitDescription {
  color: string,
  taste: string
}

通过这种设置,我无法推断出上述数据的类型。

有人可以给我更好的建议来解决这类问题吗?谢谢你的帮助。

标签: javascripttypescript

解决方案


看起来您的类型注释中缺少一系列水果描述。

type Fruit = Record<string, FruitDescription[]>

推荐阅读