Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript how to dynamically access methods of a class using variables as

How can i make TS work with this code?

export class Bla {
  do1() {
    return 1;
  }

  do2() {
    const lista = ['do1'];
    lista.every((i): string => {
      return this[i](); ->>Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Bla'. No index signature with a parameter of type 'string' was found on type 'Bla'
    });
  }
}

The error occurs in the this.
I saw this similar question but in my case in not an abstract class. I also read this keyof which might be a way to solve this, but i can’t figure it out.
Anyone knows how to solve this TS error? Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use an array as const. It’s going to be like this:

export class Bla {
  do1() {
    return 1;
  }

  do2() {
    const lista = ['do1'] as const;   // <- Here
    lista.every((i) => {
      return this[i]();
    });
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading