31

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
}
1
  • 1
    can you not create an object which has a map of string->IValue? Commented Jun 15, 2015 at 8:52

1 Answer 1

78

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You You just saved me so much agony and grief trying to get redux-form working in TypeScript!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.