Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 673
mvermand Avatar asked Oct 13 '16 19:10

mvermand


People also ask

How do you use a decorator in TypeScript?

Using Decorator Syntax In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.

What are class decorators in TypeScript?

The TypeScript website describes it as: “A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.” I would describe it as “a special declaration to add extra features on an existing class declaration, method, accessor, property, or parameter.”

What are parameter decorators in Angular?

Parameter decorators are applied to the constructor parameter of the class and are used when we need to tell Angular to inject a particular provider in a constructor. @Inject() is a widely used parameter decorator. We use this decorator to inject services in Angular classes.

When coding in TypeScript What must the name of a decorator match?

In TypeScript, decorators are declared using an at sign ( @ ) before the decorator name and have a matching function that implements the behavior. The file below contains an example of a class decorator ( @classDecorator ) applied to the class Person .


1 Answers

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.

like image 149
Nitzan Tomer Avatar answered Oct 15 '22 12:10

Nitzan Tomer