Home > OS >  How to use decoration in TypeScript?
How to use decoration in TypeScript?

Time:10-31

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

CodePudding user response:

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;
  };
}
  • Related