Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define Object of Objects type in typescript

Tags:

typescript

I have an object to store cached data which should look like this:

private data = {    'some_thing': new DataModel(),    'another_name': new DataModel() } 

I'm trying to assign an empty object to it in the constructor:

this.data = {}; // produces build error 

Basically, i need to define the type of "data" field to say that it's going to have keys with random names and values of type DataModel. I've tried to do this:

private data: Object<DataModel> 

But this is invalid. How would i specify a correct type?

like image 496
marius Avatar asked Aug 29 '16 13:08

marius


People also ask

How do you assign an object 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 define an array of object types in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!


1 Answers

It should be:

private data: { [name: string]: DataModel }; 

And then this should work:

this.data = {}; 
like image 175
Nitzan Tomer Avatar answered Oct 05 '22 15:10

Nitzan Tomer