Search code examples
javascripttypescripttype-deduction

Type Detection in TypeScript


Is there a way to get the name of a type of a caller of a function in TypeScript? Alternatively is there a way to get the name of the type of the current object?

Something like:

export class SomeData {
    sampleFunc() {
        console.log(this.getTypeName());
    }

    //or
    anotherFunc(caller: any) {
        console.log(caller.getTypeName());
    }
}

getTypeName is the desired functionality here. The types in TypeScript vanish after compiling. There is typeof (to get the class definition object itself) but I can not see how to get the name.

One usage for this could be cleaner logging with console.group(name) and console.groupEnd() - at least at development time.

Edit:

As far as I've searched, there is a Polyfill for Metadata Reflection API proposal "to add Decorators to ES7, along with a prototype for an ES7 Reflection API for Decorator Metadata". One can use that cooperatively along with decorators in TypeScript.


Solution

  • For my purposes I use:

    caller.constructor.name
    

    For more information you can read this excellent post: How to get a JavaScript object's class?