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 }
Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} . Index signatures are used when we don't know all of the names of a type's properties and the type of their values ahead of time.
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
Syntax. var object_name = { key1: “value1”, //scalar value key2: “value”, key3: function() { //functions }, key4:[“content1”, “content2”] //collection }; As shown above, an object can contain scalar values, functions and structures like arrays and tuples.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With