Search code examples
typescriptintrospection

Typescript - Cannot list methods over an Object


I have a class like this:

export class A {

    @Decorator()
    public a(): void {
        ...
    }

    @Decorator()
    public b(): void {
        ...
    }

}

Later, having an instance of A (passed in as an Object though), I want to list all its methods. I thought that Reflect.ownKeys( aInstance: Object ) could give me what I wanted, but the resulting array coming from the function is empty. What am I doing wrong?


Solution

  • That's because in javascript the methods are part of the prototype of the constructor.

    It's easier to see why if you look at the compiled javascript, for example this:

    class A {
        public a(): void {}
    
        public b(): void {}
    }
    

    Compiles to:

    var A = (function () {
        function A() {
        }
        A.prototype.a = function () { };
        A.prototype.b = function () { };
        return A;
    }());
    

    So:

    let a = new A();
    console.log(Object.keys(a)); // []
    console.log(Object.keys(a.constructor.prototype)); // ["a", "b"]
    console.log(Object.keys(A.prototype)); // ["a", "b"]