Mark a Function Parameter as Optional
Similar to last time, adding a ?
will mark last
as optional:
export const getName = (first: string, last?: string) => {
There is a caveats, however.
You can't 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 you would then have to pass undefined
as the second argument.
Transcript
Here we go. We now have a little extra character in there. Very similar to exercise number three, you can make arguments optional by just adding this little character there. If I remove this, I obviously get the same error there before.
There are some caveats too. For instance, I can't do this. I can't make the optional argument go before the required argument, and it gives me a nice little nice, little error message here. "Required parameter cannot follow an optional parameter."
This is very, very similar to how we declared it in the object type. Using it here, we can use the same trick if we want to, string or undefined, like this, but I would need to then pass undefined as the second argument. Whereas using this, it means you just don't need to pass it at all.