Home > Net >  why does a decorated static method in an abstract class returns undefined
why does a decorated static method in an abstract class returns undefined

Time:05-27

I have a decorator and I've used it in some methods in different services and it is working as expected.

I created an abstract class that have a static method and decorated it with the same decorator as mentioned above.

export function MyDecorator(): MethodDecorator {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    const original = descriptor.value;

    descriptor.value = function (...args) {
      if (args[0].message) 
        args[0] = { ...args[0], message: parse(args[0].message) };

      original.call(this, ...args);
    };
  };
}
export abstract class MyAbstractClass {
  @myDecorator()
  static decoratedMethod(param) {
    return 'Yeah Baby!';
  }
}

I then call this method inside my component like such...

  const result = MyAbstractClass.decoratedMetod('meh');

and it returns undefined. Once I comment out the decorator in the abstract class, it then returns the string 'Yeah baby!' as expected.

What am I missing here?

CodePudding user response:

You've done it right but you forgot to return the call to the original value:

    descriptor.value = function (...args) {
      if (args[0].message) 
        args[0] = { ...args[0], message: parse(args[0].message) };

      // only called, value is not used
      original.call(this, ...args);
    };

which you can fix by adding 7 more characters:

return original.call(this, ...args);
^^^^^^^

Playground

  • Related