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

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


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