How to add parameters to a class decorator in TypeScript?

mvermand picture mvermand · Oct 13, 2016 · Viewed 10.8k times · Source

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?

Answer

Nitzan Tomer picture Nitzan Tomer · Oct 13, 2016

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.