Essential Types And Notations 20 exercises
solution

Optional Function Parameters in TypeScript

TypeScript provides a first-class way to make function parameters optional.

By adding a question mark ? to the end of a parameter, it will be marked as optional:


function concatName(first: string, last?: string) {
...

With this change, the errors go away and we get nice aut

Loading solution

Transcript

00:00 TypeScript gives us a first class way to make function parameters optional here on the concat name function. We can say last and instead of just having it as string here by default. This is always required. You have to always pass this. You can make it optional with a question mark before the colon.

00:18 This means then that you get really, really nice autocomplete and kind of all of the errors that we had before go away. Concat name down here. Now we can see if we hover over it, we got first, which is required, and then last, which is not required. Very nice.

00:32 And we can see if I zoom out here that if we hover over last, it's now string or undefined. We'll get to this or symbol kind of a little bit later. This means that last could be string or it could be undefined. And it means then that we can actually pass undefined into that slot if we want to, which is quite useful too. So this is a really nice way where you can make function parameters optional. Really, really key to know in TypeScript.