TypeScript 箭头函数和装饰器

TypeScript Arrow functions and Decorators

我正在尝试尝试是否可以像这个例子一样在 TypeScript 中装饰箭头函数:

function decorateThisFunction() {        
    return (target: any, propertyKey: any, descriptor?: any) => {        
        console.log("This is my decorator do bar!");
    }
}

@decorateThisFunction
export const foo = (): void => {
    console.log("My Arrow Function");
};

如果这不可能,人们是否推荐任何替代方法?

引自官方文档:

A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.

因此,如果您需要装饰器,则必须将其附加到 class:

function decorateThisFunction(target: any, propertyKey: any, descriptor?: any): void {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
        console.log("This is my decorator do bar!");
        originalMethod(...args);
    }
}

class SomeClass {
    @decorateThisFunction
    static foo(): void {
        console.log("My Arrow Function");
    }
}

SomeClass.foo();

TypeScript playground

如果不使用 class,您可以简单地使用高阶函数:

function decorateThisFunction(func: (...args: any[]) => any) {
    return function(...args: any[]) {
        console.log("This is my decorator do bar!");
        func(...args);
    }
}

export const foo = decorateThisFunction((): void => {
    console.log("My Arrow Function");
});

foo();

TypeScript playground