hex
hex

Reputation: 515

How to constraint an optional param with another in typescript

I have the following function

        private map(model: Model, id?: number, someVariable?:number) {... }

My problem is that if id exists then someVariable must exist. If not, the logic in this method will not work and an exception will arise.

One of the solutions is to set the two variables in a class. However, I am wondering if there is such capability in typescript.

I am using Typescript 2.0.3.

Upvotes: 2

Views: 125

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 38046

You can use function overloading for this:

map(model: Model);
map(model: Model, id: number, someVariable:number);
map(model: Model, id?: number, someVariable?:number) {
    //implementation
}

Then actual implementation signature is not callable:

this.map(m); //valid
this.map(m, 1, 2); //valid
this.map(m, 1); //error

Upvotes: 3

Related Questions