Esteban Torres
Esteban Torres

Reputation: 71

What is the correct way of declaring the type in an object where the key is a string and the value is an array of objects in Typescript?

let colors = {
    "blue" : [
        {
            title: "blue",
            summary : "blue is ...",
            image : "image of blue", // this is an optional option
            link : "https:// ..."
        }, 
        {
            title: "blue",
            summary : "blue is ...",
            link : "https:// ..."
        }
    ], 
    "yellow" : [{ ... }]
}

This is an example of the structure I want to type, but I'm having trouble with it.

Upvotes: 1

Views: 22

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20376

To take advantage of TS you will have to define a separate interface for your color property objects.

interface colorProp {
            title: string;
            summary : string;
            image? : string;
            link : string;
} ;


let colors : {
    [key : string] : colorProp[]
}= {
    "blue" : [
        {
            title: "blue",
            summary : "blue is ...",
            image : "image of blue", // this is an optional option
            link : "https:// ..."
        }, 
        {
            title: "blue",
            summary : "blue is ...",
            link : "https:// ..."
        }
    ], 
    "yellow" : [{ ... }]
}


Playground

Upvotes: 2

Related Questions