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”。
在最后一种情况下getData,编译器将字段视为属性(不是纯方法)。这意味着descriptor参数不会在编译的 javascript 文件中传递。
您所需要的只是修改您的装饰器并使descriptor字段可选。考虑这个例子:
function dataMethod(name: string, options: any) {
return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里修改了你的例子
祝你好运
| 归档时间: |
|
| 查看次数: |
4417 次 |
| 最近记录: |