Search code examples
typescriptintrospection

TypeScript: Getting a class/constructor of the object at runtime


For debugging purposes, I want a toString() method of an abstract class to print of which subclass the instance actually is.

abstract FrameModel {
    ...
    public toString() {
        var classOfThis = ?????;
        return `FrameModel<${classOfThis}>#${this.vertexId}`;
    }
}

Also it would be great if I could use that class in TypeScript to access the static members; in other words, if I got the JavaScript constructor function to which TypeScript puts the static fields.

I've tried

var classOfThis = Object.getPrototypeOf(this).constructor;

But that's not it :)


Solution

  • Using Object.getPrototypeOf(this).constructor does indeed work:

    type AConstructor = {
        new(): A;
        name: string;
    }
    
    abstract class A {
        toString(): string {
            return `class: ${ (Object.getPrototypeOf(this).constructor as AConstructor).name }`;
        }
    }
    
    class B extends A {}
    
    class C extends A {}
    
    let b = new B();
    console.log(b.toString()); // class: B
    
    let c = new C();
    console.log(c.toString()); // class: C
    

    (code in playground)

    I'm not sure why it doesn't for you, I'll need to see more of your code.
    In any case, you can also use: this.constructor:

    toString(): string {
        return `class: ${ (this.constructor as AConstructor).name }`;
    }