如何在TypeScript中将其他参数传递给属性修饰器?

Joh*_*isz 10 decorator typescript

我有这个简单的类,其属性具有应用于它的属性装饰器:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

和装饰功能:

function collectionMember(target: Object, propertyKey: string | symbol): void {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如何将其他参数传递给装饰器函数?我尝试了以下但无济于事:

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

显然,这会产生错误

提供的参数与呼叫目标的任何签名都不匹配.

tos*_*skv 21

它可以通过使用装饰工厂来完成.

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以按照你的描述使用它.

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

    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 是否可以从装饰器@collectionMember访问类MyClass的另一个属性?假设我在`MyClass`中声明了`app`,是否可以从装饰器中访问`app`? (2认同)