首页 > 解决方案 > 打字稿中的装饰器引发编译错误

问题描述

我正在尝试在打字稿中测试装饰器,但是当我编译 ts 代码时出现错误

error TS1241: Unable to resolve signature of method decorator when called as an expression.

error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.

我在 tsconfig.json 中有正确的装饰器配置

{
  "compilerOptions": {
      "target"                  : "ES5",
      "experimentalDecorators"  : true,
      "emitDecoratorMetadata"   : true
  }
}

我已经尝试了在互联网上找到的所有东西来解决这个问题,但错误没有发生

tsc 版本 3.4.2

根据一篇帖子的问题,是因为在调用装饰器时编译 os ts 代码时,调用它时少了一个参数

__decorate([
        f()
    ], C.prototype, "ffolow");

使用装饰器的类是

class C {

  @f()
  ffolow() {
    console.log("FF called")
  }

}

标签: typescriptdecorator

解决方案


这取决于你的装饰器是如何定义的。假设它只是一个“常规”装饰器(不是装饰器工厂),那么你应该在不带括号的情况下应用它:

function f(target: any, propertyName: string, descriptor: PropertyDescriptor) {
  //
}

class C {

  @f
  ffolow() {
    console.log("FF called")
  }

}

推荐阅读