代码之家  ›  专栏  ›  技术社区  ›  mvermand

如何在TypeScript中将参数添加到类修饰符?

  •  20
  • mvermand  · 技术社区  · 8 年前

    我想为可以接受参数的类创建一个decorator函数。

    实例

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

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

    TS2346:提供的参数与调用目标的任何签名不匹配

    2 回复  |  直到 8 年前
        1
  •  34
  •   Nitzan Tomer    8 年前

    如果希望装饰器接收参数,则装饰器函数需要返回实际的装饰器函数:

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

    ( code in playground )

    我把名字改成了 PluginDecorator 因为 Plugin 已经存在,编译器会对此名称进行投诉。

        2
  •  0
  •   Graeme Wicksted    2 年前

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

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