我使用的是打字稿,我需要取消使用一个类型来描述这种数据格式:
{
"apple": [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}],
"banana":[{"color": "yellow","taste": "okay"}]
}
这就是我现在拥有的,我声明了一个Fruit类型,并使用Record使其成为了一个地图,然后我添加了字符串作为键(这将是诸如苹果,香蕉之类的水果名称)并声明了类型/接口{ {1}}类为Fruit的值。
FruitDescription
通过这种设置,我无法推断上述数据的类型。
有人可以给我更好的解决此类问题的建议吗?谢谢您的帮助。
答案 0 :(得分:2)
您的类型注释中似乎缺少一系列水果描述。
type Fruit = Record<string, FruitDescription[]>
答案 1 :(得分:1)
连同已经提到的 AdamExchange ,如果您具有如下定义的接口
interface FruitDescription {
color: string;
taste: string;
}
您还可以尝试以下两个选项-
const m: { [name: string]: FruitDescription[] } = {
"apple": [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}],
"banana":[{"color": "yellow","taste": "okay"}]
};
或 ,您可以使用ES6/Typescript
Map
-
let map : Map<string, FruitDescription[]> = new Map<string, FruitDescription[]>();
map.set("apple", [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}])
map.set( "banana", [{"color": "yellow","taste": "okay"}])
console.log(map.get("apple"));