Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do dynamic objects in TypeScript

Tags:

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 } 
like image 709
gevik Avatar asked Jun 15 '15 08:06

gevik


People also ask

How do you add dynamic properties to object TypeScript?

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.

How do you assign values to objects in TypeScript?

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.

How do you create a object in TypeScript?

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.


1 Answers

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.

like image 150
Slawek Avatar answered Oct 26 '22 01:10

Slawek