本文介绍了如何在TypeScript中将其他参数传递给属性装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的类,其属性具有应用于它:

I have this simple class with a property that has a property decorator applied to it:

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

    // ...
}

还有装饰器函数:

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

如何将其他参数传递给装饰器功能?我尝试执行以下操作无济于事:

How can I pass additional arguments to the decorator function? I tried doing the following with no avail:

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

    // ...
}

显然,这产生错误


推荐答案

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

It can be done by using a decorator factory.

工厂只是一个接收所需参数并返回带有修饰符签名的函数的函数:

The factory, is just a function that receives any parameters you want and returns a function with a decorator signature:

// 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];

    // ...
}

这篇关于如何在TypeScript中将其他参数传递给属性装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:51