打字稿装饰器和箭头函数

Raa*_*esh 4 typescript typescript1.5

我正在尝试实现一个 Typescript 方法装饰器,如下所示。

function dataMethod(name: string, options: any) {        
    return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {        

    }
}
Run Code Online (Sandbox Code Playgroud)

其使用如下。

class HelloWidgetExtesion {         
    @dataMethod("getData", {})
    public getData(name: any, cb: any) {
        cb(null, "");
    }
}
Run Code Online (Sandbox Code Playgroud)

但我试图弄清楚如何使用装饰器和箭头函数实现,如下所示。

class HelloWidgetExtesion {         
    @dataMethod("getData", {})
    public getData = (name: any, cb: any) => {
       cb(null, "Greetings from Loopback!");
    }
}
Run Code Online (Sandbox Code Playgroud)

但是上面的实现在编译的时候显示如下错误。

错误 TS2322:类型“(目标:任何,propertyKey:字符串,描述符:TypedPropertyDescriptor)=> void”不能分配给类型“(目标:对象,propertyKey:字符串 | 符号)=> void”。

问题的演示。

Ole*_*uka 8

在最后一种情况下getData,编译器将字段视为属性(不是纯方法)。这意味着descriptor参数不会在编译的 javascript 文件中传递。

您所需要的只是修改您的装饰器并使descriptor字段可选。考虑这个例子:

function dataMethod(name: string, options: any) {        
    return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {        

    }
}
Run Code Online (Sandbox Code Playgroud)

在这里修改了你的例子

祝你好运

相关资源(感谢@David Sherret)

  1. 装修师签名

  • 把我打败了几秒钟:) 这是正确的。类上的箭头函数不是方法——它是一个属性——因此装饰器的实现需要与方法和属性装饰器函数签名兼容,如 Oleg 的示例所示。([见这里](http://stackoverflow.com/q/29775830/188246)属性和方法装饰器签名) (3认同)