【问题标题】:unable to resolve signature of class decorator when called as an expression当作为表达式调用时无法解析类装饰器的签名
【发布时间】:2020-01-30 23:39:03
【问题描述】:

我正在尝试遵循此示例。我无法编译它。关于如何解决问题的任何想法?

import { Component } from '@angular/core';

function log(className)
{
  console.log(className)

  return (...args) => {
    console.log("Arguments passed to this class's constructor are ", args)
    return new className(...args)
  }
}

@log
class myExampleClass
{
    constructor(arg1, arg2)
    {
      console.log("Constructor fired!")
    }
}

const myClass = new myExampleClass(5,10)

我得到的错误是。

Unable to resolve signature of class decorator when called as an expression.
  Type '(...args: any[]) => any' is not assignable to type 'typeof myExampleClass'.
    Type '(...args: any[]) => any' provides no match for the signature 'new (arg1: any, arg2: any): myExampleClass'.

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    类装饰器应用于类的构造函数,可用于观察、修改或替换类定义

    在您的示例中,您尝试替换类定义。在这种情况下,您必须返回您的 @log 装饰器应用到的同一类的类型。

    function log<T extends { new(...args: any[]): {} }>(className: T) {
      console.log(className)
      return class extends className {
        constructor(...args) {
          super(...args);
          console.log("Arguments passed to this class's constructor are ", args)
        }
      }
    } 
    

    另见:

    【讨论】:

    • 是否有关于如何修改类的示例(例如,如果它们碰巧存在包装方法等)?
    猜你喜欢
    • 2019-04-18
    • 2016-07-26
    • 2021-07-06
    • 1970-01-01
    • 2016-10-08
    • 2018-12-03
    • 2020-09-07
    • 2016-04-02
    • 1970-01-01
    相关资源
    最近更新 更多