0

This works fine AFAIK:

(function f() {
    console.log(f.name);  //logs f
})();

But some of the answers posted here are a lot longer, which makes me think that I might be missing a gotcha (In other words it works in this case, BUT ...) with the above statement?

Here's a slightly different typescript variation:

function f1() {} 
function f2(f:Function) {
   console.log(f.name);
}

f2(f1);
Ole
  • 41,793
  • 59
  • 191
  • 359
  • 4
    In your code you already know `f`'s name – mplungjan Jun 22 '18 at 14:05
  • True, but I think it should work if that were a function argument to another function as well right? – Ole Jun 22 '18 at 14:06
  • 2
    Please come up with a valid use case. – mplungjan Jun 22 '18 at 14:06
  • 1
    This surely is a duplicate: https://stackoverflow.com/a/1013279/295783 – mplungjan Jun 22 '18 at 14:07
  • The use case is when the function is the name of a Validator - See how validator decorators are defined in class validator (The typescript library). I wish to use the decorator's name directly instead of a static field name defined on a different class. – Ole Jun 22 '18 at 14:10
  • 1
    Did none of the 17 answers on that question work for your case? – Heretic Monkey Jun 22 '18 at 14:41
  • Possible duplicate of [Can I get the name of the currently running function in JavaScript?](https://stackoverflow.com/questions/1013239/can-i-get-the-name-of-the-currently-running-function-in-javascript) – Michael Freidgeim May 11 '19 at 22:57

1 Answers1

0

The Function.name property is only available in ES6/ES2015-compliant engines. So for example if you try to access it without additional configuration in Typescript you will get the error:

[ts] Property 'name' does not exist on type 'Function'.

So for typescript include es2015 in your --lib value to get the property declaration.

    {
    "compilerOptions": {
        ...
        "lib": ["es2015"],                        /* Specify library files to be included in the compilation. */
        ...
    }
Ole
  • 41,793
  • 59
  • 191
  • 359