I would like to be able to call class prototype methods using bracket notation, so that the method name can be decided at run time:
classInstance['methodName'](arg);
I am failing to do this properly with TypeScript:
class Foo {
readonly ro: string = '';
constructor() {}
fn(s: number) { console.log(s); }
}
const foo = new Foo();
const methods = ['fn'];
foo['fn'](0)
// Type 'undefined' cannot be used as an index type.
foo[methods[0]](1);
// This expression is not callable.
// Not all constituents of type 'string | ((s: number) => void)' are callable.
// Type 'string' has no call signatures.
foo[methods[0] as keyof Foo](1);
The above example is in the TS Playground.
I think that I have a reasonable understanding of what the errors mean and why the string literal in foo['fn'](0)
does not produce an error. However, I don't understand how to prevent the errors. I thought that I might be able to use Extract to build a type comprising of Function, but I've failed to do that.
How can I produce a list of typed method names over which my code can iterate? And better, is it possible for the class to export such a list so that users of the class can easily access them?
Background Information
I have a Playwright test that needs to iterate over a list of methods from a Page Object Model, producing a screenshot for each.