Mutability 12 exercises
solution

Two Ways to Create Read-Only Arrays in TypeScript

There are a couple of strategies for handling read-only arrays in TypeScript. Both are functionally identical, and your choice of which to use will ultimately come down to personal preference.

Solution 1: Add the readonly Keyword

The first approach solution is to add the readonly keyword be

Loading solution

Transcript

00:00 Okay, let's take a look at both solutions. The first solution is to basically add a read-only type before this string array here. So you end up with, instead of just array of strings, a read-only array of strings. So you can think of this read-only property as applying not to the read-only string,

00:18 but read-only string array applies to the whole thing. And now you can't push to it, you can't unshift from it. And essentially there are only sort of the things inside here, the methods on the array that don't directly modify the or mutate the array. So map is still here, reduce is still here

00:36 because that creates a copy of the array. So read-only array, really, really useful. And you can use that in a more direct way by just like you can have an array of strings like this, where you use the type helper called array, you can also specify read-only array. And that does exactly the same thing.

00:55 And it sort of like behaves in exactly the same way too. Even on hover though, it's going to show you read-only string array here, which is kind of confusing, but some people will prefer this syntax. Some people will prefer this syntax. Fundamentally, they are exactly the same. And it does kind of like, I'm not sure which one I prefer. Some days I wake up and I prefer this one,

01:15 which is the read-only array syntax, or sometimes I just like the read-only modifier. I tend to err towards what TypeScript shows in its hovers though. So I think if you're going to choose one, you probably want to choose this one here because that's what's going to display when you hover over the parameter there when you use it.

01:34 But functionally identical, up to you really.