在TypeScript类中获取方法名称

时间:2020-01-12 23:26:17

标签: typescript metadata

有没有办法在TypeScript类中获取方法/函数名称?

以下TypeScript代码旨在在运行时打印类名称和方法名称。使用this.constructor.name可以很好地使用类名,但是如何获得方法名?

export class MyClass {
    public myMethod() {
        console.log('Class name: '  + this.constructor.name);
        console.log('Method name: ' + XXX);
    }
}

2 个答案:

答案 0 :(得分:0)

如果在节点上运行,则可以通过以下方式使用caller-callsite

allerCallsite().getMethodName();

返回:

"myMethod"

答案 1 :(得分:0)

如果您想以更通用的方式(跨领域关注)来封装myMethod调用和其他调用的日志记录,则可以使用decorator

function log<A extends any[], R>(
    target: Object,
    methodName: string,
    descriptor: TypedPropertyDescriptor<(...args: A) => R>) {
    let method = descriptor.value!; // this is the wrapped function
    descriptor.value = function (...args: A) {
        // instead of methodName, method.name works as well to get its name
        console.log("Calling", methodName, "with", args, "from", target.constructor.name)
        return method.apply(target, args);
    }
}

class MyClass {
    @log
    public myMethod() { }

    @log
    public myMethod2(s: string) { return 42 }
}

new MyClass().myMethod() // Calling myMethod with Array [] from MyClass
new MyClass().myMethod2("foo") // Calling myMethod2 with Array [ "foo" ] from MyClass

这里是sample。请注意,此功能尚不稳定,必须通过experimentalDecorators编译器选项启用。