Essential Types And Notations 20 exercises
solution

Specifying Optional Properties

Similar to when we set a function parameter as optional, we can use the ? to specify that an object's property is optional.

As seen in a previous exercise, we can add a question mark to function parameters to make them optional:


function concatName(user: { first: string, last?: st

Loading solution

Transcript

00:00 You might recognize this piece of syntax from a previous exercise that back then we put it on function parameters but this time we're going to put it on object properties. We can use a question mark just there and the question mark just before the colon is an indicator to TypeScript

00:14 that you don't need to pass in this last string here. So it means that user.last is now inferred as if we hover over .last string or undefined and it means then that we don't need to pass it in

00:28 there. You'll see that on concat name here when we get autocomplete on it we can specify first we'll say John and then we can also specify last and we can pass in undefined there if we want to. That's super duper nice because it means that TypeScript sort of it lets you just be so much

00:46 more expressive. It means that if you're using optional configuration objects you can specify it as you don't need to pass this. Very very cool.