angulartypescript

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'App', if string is a method component?


How I can solve this error:

TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'App'. No index signature with a parameter of type 'string' was found on type 'App'

without // @ts-ignore as the index will be a method of the component itself? So I have no idea which as keyof typeof I should use.

this[methodCall *as keyof typeof ???* ](obj)

For a better understanding, please refer to the snippet:

@Component({
  ...
})
export class App {  
  ... 
  keyup(obj: IVariableBuilder): void {
           
     const methodCall = 'keyup_' + 'X' //   obj.variableName: here the prop is needed for delegation matter
         
     // @ts-ignore
     this[methodCall](obj); // related sub-function to the object input will be invoked
  }

  keyup_X(obj: IVariableBuilder): void {
    ...
  }
}

For complete code, please refer to StackBlitz: https://stackblitz.com/edit/stackblitz-starters-kuv3qeyt?description=An%20angular-cli%20project%20based%20on%20@angular/animations,%20@angular/common,%20@angular/compiler,%20@angular/core,%20@angular/forms,%20@angular/platform-browser,%20@angular/platform-browser-dynamic,%20@angular/router,%20core-js,%20rxjs,%20tslib%20and%20zone.js&file=src%2Fmain.ts&template=node&title=Angular%20Starter


Solution

  • You caan revamp both keyup_X and keyup_Y functions into an object/dictionary.

    keyupFunctionObj = {
      keyup_X: (obj: IVariableBuilder) => {
        this.y.inputValue = Number(this.x.inputValue) * 2; // not pure function
        this.ChangeUpdater(obj);
      },
      keyup_Y: (obj: IVariableBuilder) => {
        this.x.inputValue = Number(this.y.inputValue) / 2; // not pure function
        this.ChangeUpdater(obj);
      },
    };
    

    For the caller method, use keyof to get the string literal from the keyupFunctionObj's keys and call the function from the keyupFunctionObj dictionary by name.

    const methodCall = ('keyup_' +
          obj.variableName) as keyof typeof this.keyupFunctionObj;
    
    this.keyupFunctionObj[methodCall](obj);
    

    Demo @ StackBlitz