Mutability 12 exercises
solution

Specifying a readonly Tuple

We're working with a Coordinate tuple of numbers, and a dangerousFunction that removes the last two elements from an array of numbers.

The best way to prevent unwanted changes to the Coordinate tuple is to make it a readonly tuple:


type Coordinate = readonly [number, number];

Loading solution

Transcript

00:00 Okay, what is the magical type annotation that's going to make this go away? Well, if you think about this, our coordinates up here, this number number tuple that we have there, we're saying that this coordinate is mutable. We can actually change its members.

00:16 So we can go into my house and we can say my house is actually this coordinate instead, without the y in the middle. So I think the best way to do this is actually to say type coordinate is actually read-only. We want to make this a read-only tuple and prevent the

00:33 pop method and the unshift method and the push method, any kind of like ways to change this tuple, they shouldn't be available. So we should be able to say, okay, inside type coordinate, we can say read-only number number. And now any attempts to change this will actually not be

00:51 available. We cannot assign to one because it's a read-only property. We can't push to it. We can't say my house.pop, for instance, not even available on a read-only array. This means that these read-only tuples are a lot safer. And we actually get an error down the bottom here, which is argument of type coordinate is not assignable to parameter of type number.

01:10 So it's read-only cannot be assigned to the mutable type number array. If we wanted this to be accepted by the dangerous function, we would have to say array of numbers is a read-only number array, but then pop wouldn't actually be available. We wouldn't be able to change the array there.

01:28 So this is a really, really good way. And I would almost recommend any time that you want to use tuples, you probably actually need read-only tuples because they prevent weirdnesses like this from occurring. And actually, when I've asked about this on Twitter and spoken to people in the

01:44 community, they say, yeah, I basically only use read-only tuples. I never use the other kind because it just prevents dangerous situations like this one.