Beginner's TypeScript Section 18 exercises
solution

Denote an Optional Property

This is a one character solution.

Adding a ? before the colon tells TypeScript that the property isn't required in order for the function to work.

With this update, we don't have to pass in a last if we don't want to:

export const getName = (params: { first: string; last?: strin
Loading solution

Transcript

0:00 The trick here is to add this little character just before the colon. When I remove it, we go back to basically the problem set-up. What this does is it means that you do not need to pass this in order for this to work.

0:15 I can extract this to a type if I want to. Type params equals this, and it will work in there too. Anywhere that you can specify an object key, you can use this. It means that I can pass this last if I want to.

0:30 You notice that, without this, if I remove it again and I go on the autocomplete, there's no question mark after that last just there. Whereas, if I add that, then I get the question mark saying I could pass either a string or undefined. That little or will come up later, but it's a nice way of saying it.

0:52 An alternative, if you've got a little bit of experience with TypeScript, is you could do last or undefined here, but this means you do need to pass in something in there. I could say last is undefined, and that would make it happy, but adding that little question mark character means that I don't even need to pass the property.