简体   繁体   中英

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.

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

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 -

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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