TypeScript中方法的名称

Name of method in TypeScript

本文关键字:方法 TypeScript      更新时间:2023-09-26

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

class C {
    test() { return this.test.name; } // should return "test";
}

我可以通过扩展函数接口使其适用于函数:

interface Function {
    name: string;
}
function f() {
    return f.name; // returns "f"
}

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

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

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

它被编译成

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;
})();

只有当它是这样的时候,你才会看到它用值打印function.name

 C.prototype.test = function test() {
                             // ^__ Not anonymous anymore

我可以想到的一种方法是使用decorator并为属性设置值,比如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;
    }
}

这一切都与Typescript如何转换class有关。例如,如果你使用的是Babel,由于它转换规范的方式,你会看到它将函数引用的值按原样分配给属性描述符,因此它将保留名称。

注意:并非所有浏览器都支持Function.name(例如:旧IE),而且属性name在浏览器之间也不可写入,即不能更改名称。因此,使用另一个属性进行配置。