【问题标题】:TS1238: Unable to resolve signature of class decorator when called as an expressionTS1238:作为表达式调用时无法解析类装饰器的签名
【发布时间】:2019-04-18 06:55:20
【问题描述】:

我看到以下编译错误:

TS1238:调用时无法解析类装饰器的签名 一个表达式。

代码如下:

const fdec = function(target:any, field: any, desc: any){
  console.log('target 0 :', target);
  target.bar = 3;
  return target;
};

const fdec2 = function(){
  console.log('target 1:');
  return function(target:any, field: any, desc: any){
    console.log('target 2:', target);
    target.bar = 3;
    return target;
  }
};

@fdec
@fdec2()
class Foo {
  static bar: number
}


console.log(Foo.bar);
console.log(new Foo());

有人知道如何解决这个错误吗?

【问题讨论】:

    标签: typescript tsc typescript3.0


    【解决方案1】:

    类装饰器的签名(您可以在 lib.d.ts 中找到)必须如下:

    declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
    

    所以你的类装饰器不能有 fielddesc 参数(或者如果你打算将装饰器也用作字段装饰器,它们应该是可选的)

    const fdec = function (target: any) {
        console.log('target 0 :', target);
        target.bar = 3;
        return target;
    };
    
    const fdec2 = function () {
        console.log('target 1:');
        return function (target: any) {
            console.log('target 2:', target);
            target.bar = 3;
            return target;
        }
    };
    
    @fdec
    @fdec2()
    class Foo {
        static bar: number
    }
    
    
    console.log(Foo.bar);
    console.log(new Foo());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 2020-01-30
      • 2016-07-26
      • 2021-07-06
      • 2016-10-08
      • 2018-12-03
      • 1970-01-01
      • 2020-09-07
      相关资源
      最近更新 更多