【问题标题】:Typescript Decorators and Arrow Function打字稿装饰器和箭头函数
【发布时间】:2015-12-12 19:58:05
【问题描述】:

我正在尝试如下实现一个 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!");
    }
}

但是上面的实现在编译时会出现如下错误。

错误TS2322:类型'(目标:任何,propertyKey:字符串,描述符: TypedPropertyDescriptor) => void' 不可分配给类型 '(target: Object, propertyKey: string | symbol) => void'.

Demo of the issues.

【问题讨论】:

    标签: typescript typescript1.5


    【解决方案1】:

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

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

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

    我修改了你的例子here

    祝你好运

    相关资源(感谢@David Sherret)

    1. Decorators signature

    【讨论】:

    • 领先我几秒钟 :) 这是正确的。类上的箭头函数不是方法——它是属性——因此装饰器的实现需要与方法和属性装饰器函数签名兼容,如 Oleg 的示例所示。 (See here 用于属性和方法装饰器签名)
    • 谢谢 Oleg Dokuka 和 David Sherret!
    • 如何为 .js 文件配置它?
    猜你喜欢
    • 2018-09-30
    • 2020-03-28
    • 2022-01-17
    • 2017-01-04
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多