Programming

How to call instance methods by name on a class in Typescript

I recently wanted to parameterise a test so that it included the method to test as a parameter.

This is easy in Javascript:

const myClass = new MyClass();

['methodA', 'methodB'].forEach((methodName) => myClass[methodName]();

But when you try this naively in Typescript it fails with a message that the class cannot be indexed by the type string.

The method interfaces of the class actually form a type check that needs to be satisfied and this led me to the keyof operator which forms this type.

As I was working on a test I didn’t need a strict type check so I could simply declare my string as keyof(MyClass) and this resolved the type complaint.

If the code was actually in the production paths then I would be a bit warier of simply casting and would probably try to avoid dynamic programming because it feels like it working around the type-checking that I wanted by using Typescript in the first place.

I’m not sure how I expected this to work but I was kind of expecting the type-checker to be able to use the class definition to make the check rather than using a more generic reflection that works for objects too but at the cost of having to have more annotation of your intent.

Standard

Leave a comment