【问题标题】:Type Script decorator error TS1241: Unable to resolve signature of method decorator when called as an expressionTypescript 装饰器错误 TS1241:作为表达式调用时无法解析方法装饰器的签名
【发布时间】:2018-12-03 19:24:52
【问题描述】:

我正在学习 javascript 中的装饰器。我使用打字稿进行编译 下面是代码:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }

    @enumerable(false)
    greet() {
        return "Hello, " + this.greeting;
    }
}


function enumerable(value: boolean) {
    return 
    function(target:any,propertyKey:string,descriptor:PropertyDescriptor) {
    descriptor.enumerable = value;
    };
}

其实代码来自http://www.typescriptlang.org/docs/handbook/decorators.html 使用 tsc 编译文件时,出现以下错误:

first.ts:39:5 - 错误 TS1241:当作为表达式调用时,无法解析方法装饰器的签名。 39 @可枚举(假) 这个问题我该怎么办

【问题讨论】:

    标签: typescript


    【解决方案1】:

    即使我的 tsconfig.json 文件包含在 compilerOptions...

    "target": "es5"
    

    我仍然需要在终端的 tsc 命令中声明目标...

    $ tsc myFileName.ts --target ES5 -w --experimentalDecorators
    

    这使编译错误不会出现,并允许我的装饰器正常运行。

    【讨论】:

      【解决方案2】:

      您遇到了自动插入 ; 的经典 JS 问题。行上的单个return 将表示return; 并将退出函数,因此enumerable 函数具有void 返回类型。把return函数和return放在同一行:

      function enumerable(value: boolean) {
          return function(target:any,propertyKey:string,descriptor:PropertyDescriptor) {
          descriptor.enumerable = value;
          };
      }
      

      如果您的编辑器支持此功能,Typescript 2.9 将突出显示未使用的函数,并且您应该在装饰器中也出现错误 (Identifier expected.),因为 function 被视为函数声明并且需要名字。

      【讨论】:

      • 谢谢提香。但是,我的离线代码和你描述的一样,还是有上面的错误。再次感谢您的光临!
      • 你好,我发现即使是上面的错误,tsc生成的js文件也可以正常运行。无论如何,感谢您的回答和时间。
      猜你喜欢
      • 2016-10-08
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 2019-04-18
      • 2020-01-30
      • 2021-07-06
      • 2020-09-07
      • 2016-04-02
      相关资源
      最近更新 更多