Skip to content

Get property of initially empty object after adding properties

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 ‘{}’.

    data = {};
    const key = 1;
    for( let i = 0; i < 5; i++){
      Object.assign(data, {[i]: 'test'});
    }

    if(key in data){
      data[key] = 'test2';
      data.key = 'test2';
    }

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.