0

I'm writing a decorator that needs to access another (unknown/non-normalized) value from the same class the target property is in. Currently I have:

function MyDecorator<T>(getOtherValue: (e: T) => string) {
   return (target: any, key: string) => { /* ... */ }
}

class MyClass {
    @MyDecorator<MyClass>(e => e.otherProperty) myProperty: string;
    otherProperty: string;
}

Is it possible to write this so that the user doesn't need to specify the type (<MyClass>) on the decorator each time it's used? Or is there a better way in general to handle my use case?

1 Answer 1

1

I don't think so, unfortunately. This sort of thing has been brought up as feature requests in TypeScript's GitHub repo, but nothing has been done. There are some longstanding open issues like microsoft/TypeScript#2607, and some more recent declined issues like microsoft/TypeScript#39903.

The reason is that TypeScript's language design approach when it comes to language features with runtime effects is to only implement such features if they are are part of JavaScript, or a candidate for introduction to JavaScript. That is, once they have reached or surpassed Stage 3 of the TC39 process.

This hasn't always been the case with TypeScript, and early TS-only runtime language features like enums and decorators are outliers. This means that anything suboptimal about decorators will just sit there and stay suboptimal until and unless the tc39 proposal to add them to JavaScript reaches at stage 3... and who knows when or if that will happen. They've been in limbo for a long time now.


For now that means you should probably just continue using what you're using, unless you want to abandon decorators and start working on factory functions that take entire class constructors and do the decoration manually:

function myDecorator<C extends new (...args: any) => any>(
  ctor: C,
  prop: Extract<keyof InstanceType<C>, string>,
  getOtherValue: (e: InstanceType<C>) => string
) {
  // implement the decorator here
  MyDecorator<InstanceType<C>>(getOtherValue)(ctor.prototype, prop)
}

class MyClass {
  myProperty: string = "a";
  otherProperty: string = "b";
}
myDecorator(MyClass, "myProperty", e => e.otherProperty);

Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.