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?
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.
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!
It should be:
private data: { [name: string]: DataModel }; And then this should work:
this.data = {}; 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