ilikechocolate
ilikechocolate

Reputation: 209

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.

Upvotes: 1

Views: 416

Answers (2)

MBB
MBB

Reputation: 1685

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

Upvotes: 1

AdamExchange
AdamExchange

Reputation: 1301

It looks like there is an array of fruit descriptions which is missing in your type annotation.

type Fruit = Record<string, FruitDescription[]>

Upvotes: 2

Related Questions