Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use decoration in TypeScript?

I want to use decoration to implement this but something is wrong. I don’t know how can I get data from a function in decoration.

class CalcClass{

  @subtract(1)
  @multiply(2)
  addOne(number:number) {
      return number+1;
  }
}

console.log(new CalcClass().addOne(2))

function subtract(number:number) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.value = number - 1;
    return descriptor.value;
  };
}

function multiply(number:number) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.value = number * 2;
        return descriptor.value;
  };
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I will just assume you want to modify the return value of your function with the decorators. Then we can implement them like this:

class CalcClass{

  @subtract(1)
  @multiply(2)
  addOne(number:number) {
      return number+1;
  }
}

console.log(new CalcClass().addOne(2))

function subtract(number:number) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalFunction = descriptor.value; // save the original function

    // overwrite the function with another function that calls the original, but does some extra work
    descriptor.value = (...args: any[]) => originalFunction(...args) - number;
  };
}

function multiply(number:number) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalFunction = descriptor.value;
    descriptor.value = (...args: any[]) => originalFunction(...args) * number;
  };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading