TypeScript 5 - Apply a decorator programatically

50 views Asked by At

Is there a way to apply a decorator programmatically in TypeScript 5? It could be useful to create a decorator function that applies multiple decorators.

Previously it was relatively straightforward to create a decorator that programmatically applies multiple decorators. For example: https://stackoverflow.com/a/63837335/1112503

Now, since a decorator receives a complex context as a second parameter it looks much harder to create a function that correctly applies multiple decorators

For example to add a time decorator in this class:

class MyClass {
  @time
  method(a: number): void {
    console.log("MyClass.method()");
  }
}

TypeScript 5 compiler generates the following code:

let MyClass = (() => {
    var _a;
    let _instanceExtraInitializers = [];
    let _method_decorators;
    return _a = class MyClass {
            method(a) {
                console.log("MyClass.method()");
            }
            constructor() {
                __runInitializers(this, _instanceExtraInitializers);
            }
        },
        (() => {
            _method_decorators = [time];
            __esDecorate(_a, null, _method_decorators, { kind: "method", name: "method", static: false, private: false, access: { has: obj => "method" in obj, get: obj => obj.method } }, null, _instanceExtraInitializers);
        })(),
        _a;
})();

Is there a way to do this in TypeScript 5?

0

There are 0 answers