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?
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:Then access
instance.func.functionName
.It is not possible to use TypeScript decorators because
function.name
is readonly property.There is a hacky way:
but it is not exactly what you ask for (i.e. notice the missing prototype in the function declaration).
Edit: TypeScript compiler does not write the function name because there is no handling for
SyntaxKind.MethodDeclaration
in emitter.ts:If you want to get your hands dirty, then you can update
./node_modules/typescript/lib/typescript.js
file. Just add the last condition:and run this to test the change: