【问题标题】:Unable to resolve Class Decorator Type Error无法解决类装饰器类型错误
【发布时间】:2019-08-01 08:21:59
【问题描述】:

请帮我解决打字稿错误,我花了一天时间还没有解决。

编译后功能正常,只是TS错误。

它是表达式类型的类装饰器。我正在尝试克隆原始构造函数并在初始化之前对其进行包装和处理。

我有 2 个错误。

最后一次返回

'(...args: any[]) => T' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Function'.

一个新的运算符

'(...args: any[]) => T' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Function'.

代码:

export const test : ClassDecorator = < T extends Function >( ctor : T ) : T => {

    let orig = ctor ;

    const test = function( ...args : any[] ) : T {  

         // Processing        

         return new orig()  ;

    } ;

    return test ;


} ;

@test
Class Foo {}

非常感谢您的建议。

我尝试了很多方法来解决它,比如{ new () : T } 等等,但都没有奏效。

【问题讨论】:

  • 我猜,返回的对象应该是T类型的
  • 你能举个例子吗?我猜它可能会引发另一个错误
  • 分享new orig() 的代码
  • orig() 没有代码。如果你把这些代码放在编辑器上就可以了。
  • return new orig(); 的位置,您可能有导入或为此编写的任何函数/类

标签: javascript typescript


【解决方案1】:

经过几天的尝试,这里是解决 TS 错误的方法。

问题似乎来自 T 云,使用不同的约束子类型“XXX”进行实例化。如果 T 不清楚,无论如何都会抛出错误。

看起来像Object.create,TS 会绕过这个。

另一个错误是调用签名,键入Function 不能使用新的运算符......只有键入FunctionConstructor 才能......为什么......但是然后让新的形式prototype.constructor

这是遵循 ClassDecorator 调用签名来创建具有完整类型检查的自定义构造函数的方法。我相信到目前为止还没有任何参考资料。

export const test : ClassDecorator = < T >( ctor : T & Function ) : T => {

    let test = Object.create( ctor ) ;

    test = function( ...args : any[] ) : T {

        // Processing  

        return new ctor.prototype.constructor() ;

    } ;

    return test ;

} ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2019-06-08
    • 2022-07-09
    相关资源
    最近更新 更多