sam-xor
sam-xor

Reputation: 102

how do I define type of object containing properties only of a particular type

I have an object of type

var obj : any = {
   "ab" : new X(),
   "cd" : new X(),
   ....
   ....
}

basically all the properties in an object are of type X, but the properties are being added dynamically.

I am creating this object like below (the prop name is dynamic and not fixed)

obj[prop] = new X();

How do I define this type in typescript.

Upvotes: 2

Views: 87

Answers (1)

Paleo
Paleo

Reputation: 23682

With an indexable type:

interface Dict {
    [index: string]: X;
}

let obj: Dict = {};
obj['ab'] = new X();

Upvotes: 6

Related Questions