Get class methods in typescript

I had a very hard time getting other answers to work. They also don't cover a way to do it without an instance, if that's helpful to you as it was for me.

This is what I came up with:

SomeClass.ts

import { route } from "../../lib/route_decorator";

export class SomeClass {
    index() {
        console.log("here");
    }
}

And somefile.ts

let ctrl = require("./filepath/filename");
// This is because angular exports as `exports.SomeClass = SomeClass;`
ctrl = ctrl[Object.keys(ctrl)[0]];
let ctrlObj = new ctrl();

// Access from Class w/o instance
console.log(Reflect.ownKeys(ctrl.prototype));
// Access from instance
console.log(Reflect.ownKeys(Object.getPrototypeOf(ctrlObj)));

This works, outputting:

[ 'constructor', 'index' ]
[ 'constructor', 'index' ]

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.hasOwnProperty(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.hasOwnProperty(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 in the context of OOP; however Javascript (which is not OOP) deals with it in a different way.

Tags:

Typescript