TypeScript不提供函数名称 [英] TypeScript not providing function name
问题描述
我有一些打字稿代码,我正在做一些元编程,我需要能够访问 instance.func.name
,但TypeScript省略了函数名称编译好的JS。
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:
TypeScript:
class ClassName {
// ...
func(): ReturnType {
// ...
}
}
编译的JavaScript:
Compiled JavaScript:
// ...
ClassName.prototype.func = function () {
// ...
};
所需的JavaScript:
Desired JavaScript:
ClassName.prototype.func = function func() {
// ... ^^^^
};
是否存在我缺少的编译器选项,或者我可以在TypeScript中使用的关键字来实现此目的?
Is there a compiler option I'm missing, or a keyword I can use in TypeScript to accomplish this?
推荐答案
无法使用TypeScript装饰器,因为 function.name
readonly property 。
It is not possible to use TypeScript decorators because function.name
is readonly property.
有一个 hacky way :
class ClassName {
// ...
public func = function test() {
}
public func2() {
}
}
let instance = new ClassName();
console.log("RESULT", instance.func['name']);
但它并不是你要求的(即注意函数声明中缺少的原型)。
but it is not exactly what you ask for (i.e. notice the missing prototype in the function declaration).
编辑: TypeScript编译器不写函数名,因为没有处理 SyntaxKind.MethodDeclaration
在 emitter.ts 中:
TypeScript compiler does not write the function name because there is no handling for SyntaxKind.MethodDeclaration
in emitter.ts:
function shouldEmitFunctionName(node: FunctionLikeDeclaration) {
if (node.kind === SyntaxKind.FunctionExpression) {
// Emit name if one is present
return !!node.name;
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
// Emit name if one is present, or emit generated name in down-level case (for export default case)
return !!node.name || languageVersion < ScriptTarget.ES6;
}
}
如果你想亲自动手,那么你可以更新 ./ node_modules / typescript / lib / typescript.js
文件。只需添加最后一个条件:
If you want to get your hands dirty, then you can update ./node_modules/typescript/lib/typescript.js
file. Just add the last condition:
function shouldEmitFunctionName(node) {
if (node.kind === 173 /* FunctionExpression */) {
// Emit name if one is present
return !!node.name;
}
if (node.kind === 213 /* FunctionDeclaration */) {
// Emit name if one is present, or emit generated name in down-level case (for export default case)
return !!node.name || languageVersion < 2 /* ES6 */;
}
// MODIFIED
if (node.kind === 143 /* MethodDeclaration */) {
return true;
}
}
并运行此测试以测试更改:
and run this to test the change:
$ node ./node_modules/typescript/lib/typescript.js hello.ts
这篇关于TypeScript不提供函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!