Javascript TypeScript中方法的名称

Javascript TypeScript中方法的名称,javascript,typescript,Javascript,Typescript,我可以在TypeScript中获取方法的名称吗?例如: class C { test() { return this.test.name; } // should return "test"; } C.prototype.test = function test() { // ^__ Not anonymous anymore 我可以通过扩展函数接口使其适用于函数: interface Function { name

我可以在TypeScript中获取方法的名称吗?例如:

class C {
    test() { return this.test.name; } // should return "test";
}
 C.prototype.test = function test() {
                             // ^__ Not anonymous anymore
我可以通过扩展函数接口使其适用于函数:

interface Function {
    name: string;
}

function f() {
    return f.name; // returns "f"
}

在某种程度上,我能让这种方法也起作用吗

简短的回答是否,匿名函数没有名称

如果您关心的是编译错误,那么重写接口就足够了,因为接口是局部的。但是Typescript传输
类的方式
不会有任何实例方法的名称,因为它们只是对匿名函数的引用。i、 e

它被编译成

var C = (function () {
    function C() {
    }

    C.prototype.test = function () {
                            // ^__ There is no name for the function so 
        return this.test.name; // this will just be empty
    };
    return C;
})();
您将看到它正在打印
函数。仅当它是这样时,才会使用值打印名称

class C {
    test() { return this.test.name; } // should return "test";
}
 C.prototype.test = function test() {
                             // ^__ Not anonymous anymore
我能想到的一种方法是使用装饰器并为属性设置值,比如说
propName

interface Function {
    propName?: string;
}

function setName(target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
    descriptor.value.propName =  propertyKey;
    //or target[propertyKey].propName = propertyKey;
    return descriptor;
}

class C {
    @setName
    test() {
        return this.test.propName;
    }
}
接口函数{
propName?:字符串;
}
函数setName(target:Object,propertyKey:string,descriptor:TypedPropertyDescriptor)您将看到它将函数引用的值按原样分配给属性描述符,因此它将保留名称


注意:并非所有浏览器都支持任何方式(例如:旧版IE),而且属性
name
也不能跨浏览器写入,即不能更改名称。因此,请使用其他属性进行配置。

如果添加
接口函数{name:string;}
应该可以,不是吗?@PSL我已经尝试过了,当然,它似乎不起作用。检查:是的,没错,这个匿名函数的编译是我关心的问题。使用传统的javascript我可以只使用method.name,所以我的问题是如何在Typescript中做到这一点。我知道它是如何编译的,但我能做些什么来解决这个问题那是什么?