John Weisz
John Weisz

Reputation: 31924

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

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.

Upvotes: 17

Views: 11555

Answers (1)

toskv
toskv

Reputation: 31600

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

    // ...
}

Upvotes: 33

Related Questions