1

I would like to use the information passed to class decorator from a method decorator on the same class. Here is what the (dummy) class looks like:

@classDecorator({
  something: 'very interesting'
})
class MyClass{
  @methodDecorator({
    pure: false
  })
  someMethod() {
    ...
  }
}

Now I'm interested in using the parameter given to the classDecorator ({something: very interesting'}) from within the methodDecorator.

I was hoping I could use the Reflect API, not to no avail:

function classDecorator(info) {
  // classDecorator parameter available here as 'info'

  return function(target, propertyKey, descriptor) {
    return descriptor
  }
}

function methodDecorator(config) {
  // propertyDecorator parameter availabe here as 'config'
  return function(target, propertyKey, descriptor) {

    // I thought I could access the class' decorator params with the reflect api
    Reflect.getMetadata('custom:annotation', target)
    Reflect.getMetadata('design:type', target)
    Reflect.getMetadata('design:paramtypes', target)
    // but all of the above are undefined

    return descriptor
  }

}

Is is possible to access the classDecorator's params from within a methodDecorator on the same class?

Hoff
  • 38,776
  • 17
  • 74
  • 99
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments - This works for JavaScript. I would assume that follows on in Typescript – JGFMK Feb 17 '19 at 10:25
  • thanks @JGFMK, but that's not what I'm looking for (just describes how one can read arguments in js) – Hoff Feb 17 '19 at 19:06
  • Do you mean like dir in Python? https://stackoverflow.com/questions/5523747/equivalent-of-pythons-dir-in-javascript - I tried a few of these recently - and it didn't give me what I was after. Maybe you might find something I didn't... – JGFMK Feb 17 '19 at 19:08
  • I don't think you can the way you have it set up. I believe the method decorator runs before class decorator runs. That said, I should be able access the class decorator anytime a method (that has a decorator) gets called so long as you set the properties via `Reflect.defineMetadata` on the class decorator. Then, you do need to use `Reflect.getMetadata` on `target.constructor`. – mche Jan 07 '21 at 00:51

0 Answers0