How can I pass additional arguments to a property decorator in TypeScript?

最后都变了- 提交于 2019-12-08 15:46:43

问题


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

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

    // ...
}

And the decorator function:

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

    // ...
}

Obviously, this yields the error

Supplied parameters do not match any signature of call target.


回答1:


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

And then you can use it as you described.

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

    // ...
}


来源:https://stackoverflow.com/questions/34950923/how-can-i-pass-additional-arguments-to-a-property-decorator-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!