Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript not providing function name

I have some typescript code, and I'm doing some metaprogramming where I need to be able to access instance.func.name, however TypeScript omits the function name in the compiled JS.

TypeScript:

class ClassName {
    // ... 
    func(): ReturnType {
        // ...
    }
}

Compiled JavaScript:

// ...
ClassName.prototype.func = function () {
    // ... 
};

Desired JavaScript:

ClassName.prototype.func = function func() {
    // ...                          ^^^^
};

Is there a compiler option I'm missing, or a keyword I can use in TypeScript to accomplish this?

like image 480
azz Avatar asked Nov 11 '15 09:11

azz


People also ask

What is named function in TypeScript?

Named Functions A named function is one where you declare and call a function by its given name. Example: Named Function. function display() { console.log("Hello TypeScript!" ); } display(); //Output: Hello TypeScript. Functions can also include parameter types and return type.

Is it bad practice to use any in TypeScript?

❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.


1 Answers

A solution, once which I will not be marking as accepted, because it doesn't provide the name property, but does work with any other identifier is as follows:

function named(target: any, key: string) {
    target[key].functionName = key;
}

class ClassName {
    // ... 
    @named
    func(): ReturnType {
         // ...
    }
}

Then access instance.func.functionName.

like image 125
azz Avatar answered Oct 22 '22 07:10

azz