Essential Types And Notations 20 exercises
solution

Add a Default Parameter with `=`

To add a default parameter in TypeScript, we would use the = syntax that is also used in JavaScript.

In this case, we will update last to default to "Pocock" if no value is provided:


export const concatName = (first: string, last?: string = "Pocock") => {
return `${first} ${las

Loading solution

Transcript

00:00 So how do we solve this in JavaScript? Well, we would use an equals like this and say POCOCK there. So now this seems to be working. If we look at our tests down below, it's actually passing the tests here. So it's returning the full name, returning the first name nicely, but there is a syntax error or rather a type error.

00:19 And the type error is on the last parameter here. And this says parameter cannot have question mark and initializer. So the POCOCK thing here with the equals is the initializer and this, the question mark is the question mark. So if we remove this, what happens? Ah, well, okay, that seems to have fixed it.

00:38 We save, that's all looking good. Checking the types, type check complete. That's very nice too. So last is typed as a string here and it's equals POCOCK. We hover over its usage, you can see it's typed as string there, which is really good. So the or undefined that was there earlier actually no longer needs to be there.

00:57 And we can actually delete this piece of code too, because we know that first and last is always going to be there. So let's check, should return the full same, should return beautiful. All our tests are passing. We can even remove this little type here too. And so last can just equal POCOCK. And because TypeScript knows

01:15 that you're initializing it to a string, it understands that this should be typed as a string. TypeScript is pretty clever that way as you'll see. So this is how you do default parameters in TypeScript.