Typescript 5 class decorators add inherited class to MyClass

35 views Asked by At

I'd like to use a TS5 decorator to add an inherited class to MyClass

For Example

function InheritClassDecorator() {
  return function actualDecorator<T extends { new (...args: any[]): {} }>(
    constructor: T,
    context: ClassDecoratorContext
  ) {

    class SpecialClass {
      type = "special";
    }

    return class X extends SpecialClass {
      // psuedo code example
      // this is not actually executable.
      ...constructor.prototype
    };
  };
}


InheritClassDecorator()
class MyClass {
  name = "My fancy class";
}


console.log(new MyClass().name); // "My fancy class"
console.log(new MyClass().type); // "special"

The use case is having a property on the inherited class already instantiated when an initializer runs in a decorator for MyClass.

0

There are 0 answers