I had the following problem in TypeScript: I had to add an object with an array and key inside another object:

const shareResult = {shareResult: {['email':'']}};
shareResult.shareResult['email'] = this.addContactForm.get('contact_email')?.value;
this.note.sharestatus.push(shareResult);

This was the error I got:

error TS7053: Element implicitly has an 'any' type because expression of type '"email"' can't be used to index type '{}'

Solution

The solution was to type the result explicitly with a key. TypeScript wants to be really sure what to expect, which is actually a good thing. My end code:

    type ResultType = {
      [key: string]: any
    };
    const shareResult: ResultType = {};
    const prop = 'email';
    shareResult[prop] = this.addContactForm.get('contact_email')?.value;
    const finalResult = {shareResult};
    this.note.sharestatus.push(finalResult);
 

 

 

 

Saved you some valuable time?

Received 100 so far from 4 kind contributors.