如何向 TypeScript 中的 class 装饰器添加参数?

How to add parameters to a class decorator in TypeScript?

我想为可以带参数的 class 创建装饰器函数。

示例

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

我试过了,但没用:

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

我在 WebStorm 中收到一条错误消息:

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

这个装饰函数需要怎么写?

如果您希望您的装饰器接收参数,那么您的装饰器函数需要 return 实际的装饰器函数:

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

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

(code in playground)

我将名称更改为 PluginDecorator 因为 Plugin 已经存在并且编译器抱怨该名称。

如果您需要同时访问参数和构造函数:

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;
    };
}