⭐ 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)