mvermand mvermand - 1 year ago 147
TypeScript Question

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.


@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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download