β Optional Parameters β
Consider this getName function:
export const getName = (first: string, last: string) => {
if (last) {
return `${first} ${last}`;
}
return first;
}
It takes in first and last as individual parameters:
We will determine how to mark the last parameter as optional.
π Solution:
Similar to last time, adding a ? will mark last as optional:
export const getName = (first: string, last?: string) => {
// ...
}
There is a caveat, however.
We can not put the optional argument before the required one:
// This will not work!
export const getName = (last?: string, first: string) => {
// ...
}
This would result in "Required parameter cannot follow an optional parameter".
As before, you could use last: string | undefined but we would then have to pass undefined as the second argument.
I hope you found it useful. Thanks for reading. π
Let's get connected! You can find me on:

Top comments (0)