2

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.

Kaveh Shahbazian
  • 13,088
  • 13
  • 80
  • 139
  • Can you update with a code sample of what exactly are you trying to achieve? I know you can use caller.name but getting type isn't possible as same rules apply as for JavaScript when TypeScript is compiled. Maybe this can help you http://stackoverflow.com/a/3789144 – Matija Grcic Jan 17 '16 at 11:16
  • @MatijaGrcic Thanks; I've updated the question. BTW on chrome, the `arguments.callee.caller.name` still gives the body of the function. – Kaveh Shahbazian Jan 17 '16 at 11:27
  • 1
    you may also want to try out http://vorlonjs.io/ – Matija Grcic Jan 17 '16 at 13:07

1 Answers1

5

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?

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54