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?
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.
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.”
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With