【问题标题】:TypeScript Arrow functions and DecoratorsTypeScript 箭头函数和装饰器
【发布时间】:2022-01-17 18:10:48
【问题描述】:

我正在尝试测试是否可以像以下示例一样在 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");
};

如果这不可能,人们推荐其他方法吗?

【问题讨论】:

  • 不可能,只有当该函数是类的成员时
  • 是的,我知道我正在寻找替代品。

标签: typescript decorator typescript-decorator


【解决方案1】:

引用官方文档:

装饰器是一种特殊的声明,可以附加到 class declarationmethodaccessorpropertyparameter

所以如果你需要一个装饰器,你必须将它附加到一个类:

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

不使用类,您可以简单地使用高阶函数:

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

【讨论】:

  • 是的,我知道我正在寻找替代品。
  • 类中的static 方法不是一个方便的替代方案吗?
  • 不使用类
  • 例如const foo = () => {}
  • 不使用类,建议直接使用高阶函数
猜你喜欢
  • 2015-12-12
  • 2020-04-25
  • 1970-01-01
  • 2018-09-30
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
相关资源
最近更新 更多