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.

3
  • 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 stackoverflow.com/a/3789144 Commented Jan 17, 2016 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. Commented Jan 17, 2016 at 11:27
  • 1
    you may also want to try out vorlonjs.io Commented Jan 17, 2016 at 13:07

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

You're kidding me! :) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.