Essential Types And Notations 20 exercises
solution

Working with Optional Tuple Members in TypeScript

A good start would be to change the coordinates parameter to a tuple of [number, number, number | undefined]:


const goToLocation = (coordinates: [number, number, number | undefined]) {
...

The problem here is that while the third member of the tuple is able to be a number or `unde

Loading solution

Transcript

00:00 Okay, we know that we need to solve this probably with some tuple syntax, so we might as well add number, number, number, and see where that gets to. So we can see here that we now have latitude as a number, longitude as a number, but elevation is a number.

00:14 And if we go for number or undefined here, then this looks pretty good, except for you can see that go to location now, it's expecting you to pass undefined, because it's not actually an optional member of the tuple. It's just a member that's required but could be number or undefined, so the only way to

00:33 satisfy this is to actually manually pass in undefined, which is not particularly fun. So we need a way to specify this differently. One way you can do it is with like a named tuple here.

00:47 So we can say latitude is this, longitude is this, and elevation is the other one, so let's add that. You notice it starts looking more like an object here, curiously. And now, using this syntax, we can actually do elevation, optional member, is a number.

01:06 So this is the first method. This is pretty good, I would say. It's sort of a little bit funky, because it really looks like an object here, so if you're scanning over this, you might think, oh, that just looks like an object. And if you don't want to use named tuples for whatever reason, you can actually use this syntax instead, where you put the question mark after the definition there.

01:25 Like this, it's required. Like this, it's optional. Optional members of tuples, a funny little quirk of tuples in TypeScript.