DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #4

Image description

Optional Parameters

Consider this getName function:

export const getName = (first: string, last: string) => {
  if (last) {
    return `${first} ${last}`;
  }
  return first;
}
Enter fullscreen mode Exit fullscreen mode

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) => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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) => {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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)