I am trying to make a data converting script (with Angular) and need to access properties of an object which is initially empty (see simplified code below). However, I get an error message that says that the key does not exist in the object. I can not add the keys when initialising the object because the data might be different in the next run. I have tried different methods of accessing the key but I have not yet figured it out. I hope someone can help me!
TS7053: Element implicitly has an ‘any’ type because expression of type ‘1’ can’t be used to index type ‘{}’. Property ‘1’ does not exist on type ‘{}’.
JavaScriptx11111data = {};
2const key = 1;
3for( let i = 0; i < 5; i++){
4Object.assign(data, {[i]: 'test'});
5}
6
7if(key in data){
8data[key] = 'test2';
9data.key = 'test2';
10}
11
Advertisement
Answer
If you don’t know the property names at first, you can use any
. Initialize it like this:
data: any = {};
If you know the property types (e.g. all the properties are strings), then you can type it something like this:
data: { [key: string]: string } = {};
Then it will work.