born2net born2net - 3 months ago 15
TypeScript Question

In TypeScript how do you set an object literal that holds a certain type

In TypeScript how do you set an object literal that holds a certain type
for example if you had an array you would do:


export interface ISimpleListItem {
item: any,
index: number,
selected: boolean
}



var myArray:Array<ISimpleListItem>

which is great.

but how would you do the same with Object, as the following will not work since Object is not a Generic.

var myObject:Object<ISimpleListItem>

myObject['foo'].item <<< error since Object is not a generic

thanks,

Sean

Answer

If I understand you right then:

let myObject: { [key: string]: ISimpleListItem } = {
    "key1": {
        index: 1,
        item: "something",
        selected: true
    }
};

(code in playground)