gevik
gevik

Reputation: 3407

How to do dynamic objects in TypeScript

Is there any way to define a dynamic object type in TypeScript? In the following example, I would like to define a type for "My Complex Type" by saying:

Objects of type "My Complex Type" are objects having "any number of properties" but the values of those properties must be of type IValue.

// value interface
interface IValue {
    prop:string
}

// My Complex Type
myType = {
    field1:IValue
    field2:IValue
    .
    .
    .
    fieldN:IValue
}

// Using My Complex Type 

interface SomeType {
    prop:My Complex Type
}

Upvotes: 30

Views: 44396

Answers (1)

Slawek
Slawek

Reputation: 2632

Yes, that kind of behavior can be achieved, but in slightly different way. You just need to use typescript interface, like:

interface IValue {
    prop: string
}

interface MyType {
    [name: string]: IValue;
}

that will be used for example like:

var t: MyType = {};
t['field1'] = { prop: null };
t['field2'] = new DifferentType(); // compile-time error
...
var val = t['field1'];
val.prop = 'my prop value';

You don't have to create typescript class, Everything you need is a regular javascript object ( in that case {} ) and make it implement interface MyType, so it behaves like dictionary and provide you with compile-time type safety.

Upvotes: 77

Related Questions