Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Romain Bruckert for Typescript method is return undefined with method decorator

I don't know why all the posts on the internet reference such examples, but I had problems of my own with the method decorator context regarding originalMethod.apply(this, args);

This indeed does NOT work AT ALL (I don't know if its a ts bug or something though).

After trial an error, I found that the following solution worked, allowing you to have the correct context inside your base class:

function myDecorator(target: Object, key: string, descriptor: TypedPropertyDescriptor<any>) {        descriptor.value = function (...args:any[]) {            // whatever code suits you here...            // dont use "this", use "target"            let result = originalMethod.apply(target, args);        }        return descriptor;}

Now this allows you to do:

export class Yeah {    @myDecorator()    helloWord() {        let n = 5;        return this.multiply(n);    }    multiply(a: number) {       return a * 2;    }}

Cheers


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>