Mutability 12 exercises

Distinguishing Assignability Between Read-Only and Mutable Arrays

When working with TypeScript, it's important to understand the distinction between read-only and mutable arrays.

In this example, printNamesReadOnly and printNamesMutable, which are functionally identical, except printNamesReadOnly takes a read-only array of names as a parameter whereas `prin

Loading explainer


00:00 Now that we know about read-only arrays, it's important to distinguish between like what's assignable to what. We have two functions here called printNamesReadOnly and printNamesMutable. They're absolutely identical. They both take in an array of names, except printNamesReadOnly takes in a read-only array of names.

00:17 We're using the read-only modifier here, whereas printNamesMutable takes in a mutable array of names. Then down the bottom here, we can see that if we declare a mutable array of names, a bunch of like an array that we can push to, then we can actually pass these to the read-only one and we can pass it to the mutable one.

00:36 That's because the read-only one is only guaranteeing that it's not going to change the names, right? That's what you say when you sort of like hover over this, you see, okay, it expects a read-only array of strings. It doesn't matter if we pass a mutable array of strings, because we're not going to touch them anyway. Whereas the other way around doesn't work.

00:53 If we have a read-only names array here, which we're declaring as const, because we can declare them as const. Very cool. This means this array is now read-only John, Jane and Mike. Then it means that we can only pass them into the read-only slot. If we pass them into the mutable slots, then we're basically saying that we might change this array.

01:13 We might add stuff to it. We might fiddle around with it. And this means that we get an error here saying argument of type read-only John, Jane, Mike is not assignable to a mutable parameter of type string. You can see up here, yeah, cannot be assigned to the mutable type string. So TypeScript use this kind of like mutable stuff too. So this is how you should think about it.

01:31 Read-only is only assignable to other read-only types. And this means that, of course, like read-only is kind of viral in your application. If you have a function way down the call stack that expects something to be read-only, then you're going to make sure that that needs to be read-only all the way up, because it needs to guarantee that it's not going to be mutated anyway down the stack.

01:51 So this is basically how you can think about read-only arrays in TypeScript. Read-only arrays are not assignable to mutable arrays, but it does work the other way around.