mvermand
mvermand

Reputation: 6117

How to add parameters to a class decorator in TypeScript?

I want to create a decorator function for a class that can take a parameter.

Example

@Plugin("My first Plugin")
class myFirstPlugin {
   ...
}

I tried this, but it does not work:

function Plugin(constructor: Function, name:string){
    console.log("Plugin found: " + name);
}

I get an error in WebStorm saying:

TS2346: Supplied parameters do not match any signature of call target

How do I need to write this decorator function?

Upvotes: 24

Views: 19963

Answers (2)

Graeme Wicksted
Graeme Wicksted

Reputation: 1815

If you need to access both the parameters and the constructor:

type BaseClass = HTMLElement;

type Constructor = { new (...args: any[]): BaseClass };

export function Plugin(name: string) {
    return function <T extends Constructor>(constructor: T) {
        const cls = class extends constructor {
            // custom implementation here
        };

        // perhaps something like this
        customElements.define(name, cls, { extends: "div" });

        return cls;
    };
}

Upvotes: 3

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

If you want your decorator to receive parameters then your decorator function needs to return the actual decorator function:

function PluginDecorator(name: string) {
    return (ctor: Function) => {
        console.log("Plugin found: " + name);
    }
}

@PluginDecorator("My first Plugin")
class myFirstPlugin {}

(code in playground)

I changed the name to PluginDecorator because Plugin already exists and the compiler complains about that name.

Upvotes: 39

Related Questions