Typescript

TypeScript Optional Parameters

📣 Sponsor

In Javascript, if a function has 4 parameters, and we only use 3, it’s no big deal - Javascript just ignores the missing parameter and runs the function as if it is undefined.

In TypeScript, things are a little different. If you try to run a function with a different number of parameters than the function actually has, you’ll get an error. For example, consider this:

const myFunction = (a: string, b: string, c?: string) => { return a + " " + b + " " + c; } let runFunction = myFunction("Hello", "there");

The above code will throw the following error:

Expected 3 arguments, but got 2.

TypeScript does this to ensure fewer errors, since leaving a parameter out of a function you are calling can sometimes break the function. As such, we need to tell TypeScript specifically that one or more of the parameters we defined on the function are optional. In order to do that, we use a ? after the parameter, to denote that it is actually an optional parameter.

For example, if we wanted to make c optional on our original function, we could write the following - and not get an error:

const myFunction = (a: string, b: string, c?: string) => { return a + " " + b + " " + c; } let runFunction = myFunction("Hello", "there"); console.log(runFunction);

Now our function will run as expected, however the output will be Hello there undefined. This may not be your desired behaviour, which is exactly why TypeScript has these controls in place - it can help prevent unwanted outcomes by requiring certain parameters.

In TypeScript, however, an optional parameter cannot be followed by a required one. So for example, the following code will not work:

const myFunction = (a: string, b?: string, c: string) => { return a + " " + b + " " + c; }

It will produce the following error:

A required parameter cannot follow an optional parameter.

We can combine this optionality with the use of the typeof operator to produce code that makes sense. For example, if c is optional and undefined, then we can ignore it, like so:

const myFunction = (a: string, b: string, c?: string) => { if(c === undefined) { return a + " " + b; } return a + " " + b + " " + c; } let runFunction = myFunction("Hello", "there"); console.log(runFunction);

Now the output of our code will be Hello there, but we could also run it with c to produce a different output, for example:

const myFunction = (a: string, b: string, c?: string) => { if(c === undefined) { return a + " " + b; } return a + " " + b + " " + c; } let runFunction = myFunction("How", "are", "you?"); // Returns "How are you?" console.log(runFunction);
Last Updated 1657366615029

More Tips and Tricks for Typescript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email