James Monger
James Monger

Reputation: 10665

Get signature of method from method decorator

I have a method decorator like this:

export function NumberMethodDecorator(message: string) {
  return (target: object, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {
    // do some stuff here
  }
}

I want to apply it like so:

class SomeClass {

  @NumberMethodDecorator("do some cool stuff")
  public someMethod(value: number) {

  }

}

However, I want to ensure that NumberMethodDecorator is only applied to methods with the signature (value: number) => any.

How can I do this?

Upvotes: 2

Views: 508

Answers (1)

David Sherret
David Sherret

Reputation: 106630

Specify that in the type argument of TypedPropertyDescriptor:

export function NumberMethodDecorator(message: string) {
  return (
    target: object, propertyKey: string,
    descriptor?: TypedPropertyDescriptor<(value: number) => any>
  ) => {
    // do some stuff here
  };
}

Then when using:

class SomeClass {
  @NumberMethodDecorator("") // ok
  someMethod(value: number) {

  }

  @NumberMethodDecorator("") // compile error
  otherMethod() {
  }
}

Upvotes: 1

Related Questions