Essential Types And Notations 20 exercises

Making Object Property Types Optional

Similar to what we've seen with function parameters, we can also make object property types optional.

Here's a version of the concatName function that has been updated to return just the first name if a last name wasn't provided:

const concatName = (user: { first: string; last: st

Loading exercise


00:00 Okay, we have a similar setup to what we had before. We have a concat name function, which takes in first and last. And if the user doesn't pass the last name, then we can return user.first. Otherwise we'll return in template literal syntax, user.first and user.last with a space between.

00:17 And this is all working and it's working in the test too, except that we've got an error here. And this error is basically saying property last is missing in type first string, but required in type first string, last string. So what it's saying is we've missed off a property here.

00:34 So we need to know how we can make last here optional. So how do we declare this as an optional property type? There is some syntax that you can use. We can just edit this little piece of code just there and it will just start working. Good luck.