如何在TypeScript中向属性装饰器传递额外的参数?

17

我有一个简单的类,其中包含一个应用了属性装饰器的属性:

class MyClass {
    @collectionMember
    public myProperty: number[];

    // ...
}

装饰器函数:

function collectionMember(target: Object, propertyKey: string | symbol): void {
    // ...
}

我该如何向装饰器函数传递额外的参数?我尝试了以下方法,但没有成功:

class MyClass {
    @collectionMember("MyProp")
    public myProperty: number[];

    // ...
}

显然,这会导致错误:
提供的参数不符合调用目标的任何签名。
1个回答

33

可以通过使用装饰器工厂来完成。

这个工厂只是一个函数,它接收任何想要的参数,并返回带有装饰器签名的函数:

// any parameters, even optional ones!
function collectionMember(a: string, b?: number) {
    // the original decorator
    function actualDecorator(target: Object, property: string | symbol): void {
        // do something with the stuff
        console.log(a);
        console.log(target);
    }

    // return the decorator
    return actualDecorator;
}

然后你可以按照你所描述的方式使用它。

class MyClass {
    @collectionMember('MyProp') // 2nd parameter is not needed for this array
    public myProperty: number[] = [1, 2, 3, 4, 5];

    // ...
}

8
@collectionMember装饰器中,有没有一种访问 MyClass 类的另一个属性的方法?比如说,如果我在 MyClass 中声明了 app,我能否从装饰器内部访问 app - borislemke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接