How to define Object of Objects type in typescript

Typescript

Typescript Problem Overview


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?

Typescript Solutions


Solution 1 - Typescript

It should be:

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

And then this should work:

this.data = {};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmariusView Question on Stackoverflow
Solution 1 - TypescriptNitzan TomerView Answer on Stackoverflow