Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript decorator constructor overwriting including additional arguments

According to the typescript decorators documentation the decorator example for replacing a constructor does not pass any arguments to the decorator function. How am I able to achieve this?

This is what the doc says

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
  return class extends constructor {
    newProperty = "new property";
    hello = "override";
  }
}

@classDecorator
class Greeter {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}

But I want now to pass arguments like using the decorator as follows

@classDecorator({
  // some object properties fitting DecoratorData type
})

I simply tried to add a second data parameter

function classDecorator<T extends {new(...args:any[]): {}}>(constructor: T, data: DecoratorData)

But this just tslint 2 arguments required, got 1. Inserting a null placeholder doesn't work either. Also I tried using the constructor parameter as a second optional parameter. This leads to a signature missmatch error.

like image 738
Felix Lemke Avatar asked Mar 07 '23 18:03

Felix Lemke


1 Answers

You need to use a decorator generator, a function which returns a decorator function. The generator function can take extra arguments, and the inner decorator function can capture those parameters and use them.

function classDecorator(data: DecoratorData) {
    return function <T extends { new(...args: any[]): {} }>(constructor: T) {
        return class extends constructor {
            newProperty = "new property";
            hello = "override";
            // use daat here 
        }
    }
}

@classDecorator({ data: "" })
class Greeter {
    property = "property";
    hello: string;
    constructor(m: string) {
        this.hello = m;
    }
}
like image 108
Titian Cernicova-Dragomir Avatar answered May 02 '23 18:05

Titian Cernicova-Dragomir