hex hex - 2 months ago 8
TypeScript Question

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.

Answer

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