Home > front end >  Typescript how to dynamically access methods of a class using variables as
Typescript how to dynamically access methods of a class using variables as

Time:08-25

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.

CodePudding user response:

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]();
    });
  }
}
  • Related