#Modify method signature using decorators

11 messages · Page 1 of 1 (latest)

crisp cosmos
#

Can I modify a method signature using stage 3 decorators? I have a method that receives 2 arguments

steady matrix
#

however, you can manipulate the arguments inside the decorator before passing them to the original method

#

for example, if you wanna modify the way arguments are passed to a method

#
function ModifyArgs() {
  return function (
    target: any,
    context: ClassMethodDecoratorContext
  ) {
    return function (this: any, ...args: any[]) {
      console.log('Original args:', args);
      
      // Modify arguments
      const newArgs = args.map(arg => String(arg).toUpperCase());

      return target.apply(this, newArgs);
    };
  };
}

class Example {
  @ModifyArgs()
  greet(name: string, message: string) {
    console.log(`Hello, ${name}: ${message}`);
  }
}

const e = new Example();
e.greet('John', 'welcome'); 
// Logs: "Hello, JOHN: WELCOME"
crisp cosmos
#

Thanks Dan! Hmmm so if I want to add parameters (For example, I wanna add a name + message param to the function) you'd suggest passing it inside some object as a "named parameter"?

steady matrix
#

if you wanna add extra parameters dynamically, you'd typically wrap them in an object and mdify that inside the decorator

#

that way, you are not messing with the method signature directly but still achieving the flexibility you need

#
function AddParams(extraParams: Record<string, any>) {
  return function (target: any, context: ClassMethodDecoratorContext) {
    return function (this: any, ...args: any[]) {
      console.log('Original args:', args);

      // Inject extra parameters
      const modifiedArgs = [...args, extraParams];

      return target.apply(this, modifiedArgs);
    };
  };
}

class Example {
  @AddParams({ extra: 'Some additional info' })
  greet(name: string, message: string, extraParams?: Record<string, any>) {
    console.log(`Hello, ${name}: ${message}`);
    if (extraParams) {
      console.log('Extra params:', extraParams);
    }
  }
}

const e = new Example();
e.greet('John', 'welcome');
// Logs: "Hello, John: welcome"
// Logs: "Extra params: { extra: 'Some additional info' }"
#

you know, since typescript enforces method signatures at compile time, you cant directly modify them at runtime