In a previous article, I covered the concept of optional parameters in TypeScript. In this guide, we used the ?
question mark symbol to denote if a function's argument was optional.
In this guide, let's look at another way of achieving this - with default parameters.
Default Parameters
Before looking at how these parameters work in TypeScript, lets recap on how they work in Javascript. Default parameters are already widely supported in Javascript. When we talk about default parameters, we are talking about giving arguments values that should be used, if that argument is undefined. For example:
let myFunction = (x, y = "World") => {
console.log(x + " " + y);
}
myFunction("Hello");
In the example above, since y
is undefined when we call myFunction
, the default value is used. That avoids the issue where y
may be undefined
if the user doesn't mention it in the function. If we didn't define y
here, then the function above would console log Hello undefined
.
Why use Default Parameters?
The example above is a good reason as to why you might want to use default parameters. Here, we don't want the user to see an undefined
value. So we will replace y
with a default, meaning we never show this to user. Imagine a similar scenario where we show a user's name. In that example, we might not always have the surname. Here, we could use default values to omit it and not show the text undefined
to the user:
let showName = (firstName, lastName = "") => {
return firstName + " " + lastName
}
As such, default parameters let us improve a user's experience in some cases. They also can be used in other places, such as setting the default position of a shape on an HTML canvas.
Default Parameters in TypeScript
Fortunately, there isn't much added complexity in TypeScript when it comes to default parameters. We can add them into our code in the same way - we just also define the types too.
let myFunction = (x: string, y: string = "World") => {
console.log(x + " " + y);
}
myFunction("Hello");
Here, we expect both arguments to be strings, but actually, we don't even have to give y
a type. TypeScript's engine will infer that y
is a string, since its default value is a string:
let myFunction = (x: string, y = "World") => {
console.log(x + " " + y);
}
myFunction("Hello");
That means that running myFunction("Hello", 1)
will still result in a TypeScript error - even if we don't explicitly define y
's type:
Argument of type 'number' is not assignable to parameter of type 'string'.
Conclusion
In conclusion, default parameters can be used the same way as in Javascript. The only additional thing to consider is that we don't have to always define a type on a parameter that has a default value, and if we don't, TypeScript will assume the type based on what the default value is. So if the default value was 1
, then TypeScript would assume that that argument was a number
.