hex hex - 11 months ago 45
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
exists then
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 Source

You can use function overloading for this:

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

Then actual implementation signature is not callable:

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