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?
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.
❌ 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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With