简体   繁体   English

打字稿声明地图类型

[英]typescript declare map type

I am using typescript and I need to decare a type to describe this format of data:我正在使用打字稿,我需要定义一个类型来描述这种数据格式:

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

This is what I have right now, I declared a type Fruit and made it a map using Record and then I added string as key(which is going to be fruit name like apple, banana) and declared a type/interface FruitDescription class as Fruit's value.这就是我现在所拥有的,我声明了一个 Fruit 类型并使用 Record 将其设为映射,然后我添加了字符串作为键(这将是苹果、香蕉等水果名称)并声明一个类型/接口FruitDescription类作为 Fruit 的价值。

type Fruit = Record<string, FruitDescription>

interface FruitDescription {
  color: string,
  taste: string
}

With this set up I am not able to deduce the type of the data mentioned above.通过这种设置,我无法推断出上述数据的类型。

Can someone give me any better suggestion for solving this kind of issue?有人可以给我任何更好的建议来解决此类问题吗? Thank you for help.谢谢你的帮助。

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

type Fruit = Record<string, FruitDescription[]>

Along with what AdamExchange already mentioned, If you have an interface defined like below连同AdamExchange已经提到的,如果你有一个如下定义的接口

interface FruitDescription {
  color: string;
  taste: string;
}

You could also try the below two options -您也可以尝试以下两个选项 -

const m: { [name: string]: FruitDescription[] } = {
   "apple": [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}],
   "banana":[{"color": "yellow","taste": "okay"}]
};

Or you could use ES6/Typescript Map -或者你可以使用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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM