简体   繁体   中英

Unable to resolve Class Decorator Type Error

please help my for the typescript error, it spends me a day havent resolved yet.

The function works fine after compiler, just the TS error.

Its a Class Decorator in expression type. I am trying to clone original constructor and wrap it and process something before initializing.

I got 2 errors.

One on last return

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

One on new operator

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

Code :

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 {}

Thank you very much for your advise.

I tried a lot of way to resolve it like { new () : T } and etc. none of them worked.

After days try, here is the way to resolve TS error.

The issue seems like from T cloud be instantiated with a different subtype of constraint 'XXX'. If T is not clear, it throws error no matter what.

Looks like with Object.create , TS will bypass this one.

Another error is the call signature, type Function cannot use new operator...... only type FunctionConstructor can..... why..... but then lets new form prototype.constructor .

This is the way to follow ClassDecorator call signature to crate custom constructor with full type checking. I believe so far no reference anywhere yet.

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 ;

} ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM