打字稿装饰器和箭头功能
Typescript Decorators and Arrow Function
我正在尝试按如下方式实现 Typescript 方法装饰器。
function dataMethod(name: string, options: any) {
return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
}
}
其用法如下。
class HelloWidgetExtesion {
@dataMethod("getData", {})
public getData(name: any, cb: any) {
cb(null, "");
}
}
但我正在尝试弄清楚如何使用带有箭头函数实现的装饰器,如下所示。
class HelloWidgetExtesion {
@dataMethod("getData", {})
public getData = (name: any, cb: any) => {
cb(null, "Greetings from Loopback!");
}
}
但是上面的实现在编译的时候出现如下错误。
error TS2322: Type '(target: any, propertyKey: string, descriptor:
TypedPropertyDescriptor) => void' is not assignable to type
'(target: Object, propertyKey: string | symbol) => void'.
在最后一种情况下,字段 getData
被编译器视为 属性(不是纯方法)。
这意味着 descriptor
参数不会在已编译的 javascript 文件中传递。
您所需要的只是修改装饰器并使 descriptor
字段可选。考虑这个例子:
function dataMethod(name: string, options: any) {
return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
}
}
我修改了你的例子here
祝你好运
相关资源(感谢@David Sherret)
我正在尝试按如下方式实现 Typescript 方法装饰器。
function dataMethod(name: string, options: any) {
return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
}
}
其用法如下。
class HelloWidgetExtesion {
@dataMethod("getData", {})
public getData(name: any, cb: any) {
cb(null, "");
}
}
但我正在尝试弄清楚如何使用带有箭头函数实现的装饰器,如下所示。
class HelloWidgetExtesion {
@dataMethod("getData", {})
public getData = (name: any, cb: any) => {
cb(null, "Greetings from Loopback!");
}
}
但是上面的实现在编译的时候出现如下错误。
error TS2322: Type '(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => void' is not assignable to type '(target: Object, propertyKey: string | symbol) => void'.
在最后一种情况下,字段 getData
被编译器视为 属性(不是纯方法)。
这意味着 descriptor
参数不会在已编译的 javascript 文件中传递。
您所需要的只是修改装饰器并使 descriptor
字段可选。考虑这个例子:
function dataMethod(name: string, options: any) {
return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
}
}
我修改了你的例子here
祝你好运