tcoder01 tcoder01 - 7 months ago 53
TypeScript Question

Get class methods in typescript

I am running typescript unit tests with mocha chai (after setting the compiler options to ts-node).

In one of my unit tests, I would like to get all the methods of a utility class that I have created and run the same tests on them.
To be more concrete, I would like to achieve something like this:


Is there a way to implement getMethods elegantly? Or maybe, another way to tackle this need?


You forget that TypeScript is Javascript. Remember that the TypeScript compiler compiles your code into Javascript.

So, as you normally do in Javascript, you can enumerate members on an object like this:

UtilityClass myclass = ...;

for (var member in myclass) { /* do something */ }

More advanced

If you want to make sure you don't get inherited members:

for (var member in myclass) {
  if (myclass.hasOwnedProperty(member)) {
    /* do something */

Extract methods

If you want to make sure you get only methods (functions):

for (var member in myclass) { // For each member of the dictionary
  if (typeof myclass[member] == "function") { // Is it a function?
    if (myclass.hasOwnedProperty(member)) { // Not inherited
      // do something...

Reflection in TypeScript

As you can see the approaches require an instance to work on. You don't work on the class. Reflection is what you are trying to achieve, but in Javascript this is not really the case.