Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Decorators and Arrow Function

I'm trying to implement a Typescript method decorator as follows.

function dataMethod(name: string, options: any) {        
    return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {        

    }
}

And its used as below.

class HelloWidgetExtesion {         
    @dataMethod("getData", {})
    public getData(name: any, cb: any) {
        cb(null, "");
    }
}

But I'm trying to figure out how to use decorators with Arrow function implementation as below.

class HelloWidgetExtesion {         
    @dataMethod("getData", {})
    public getData = (name: any, cb: any) => {
       cb(null, "Greetings from Loopback!");
    }
}

But the above implementation shows the following error when compiling.

error TS2322: Type '(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor) => void' is not assignable to type '(target: Object, propertyKey: string | symbol) => void'.

Demo of the issues.

like image 389
Raathigesh Avatar asked Feb 09 '23 01:02

Raathigesh


1 Answers

In the last case field getData is considered by compiler as property (not pure method). This means that the descriptor arguments would not be passed in compiled javascript file.

All that you need it is modify your decorator and make descriptor field optional. Consider this example:

function dataMethod(name: string, options: any) {        
    return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {        

    }
}

I have modified your example here

Good Luck

Related Resources (thanks for it @David Sherret)

  1. Decorators signature
like image 148
Oleh Dokuka Avatar answered Feb 18 '23 06:02

Oleh Dokuka