Mutability 12 exercises
explainer

Use the ts-reset Library to Improve Readonly Array Handling in TypeScript

Working with read-only arrays in TypeScript can be slightly annoying, especially when you're working with the includes and indexOf methods.

Take a simple read-only users array declared with as const:


const users = ["matt", "sofia", "waqas"] as const;

A common operation cou

Loading explainer

Transcript

00:00 A slightly annoying property of read-only arrays is that the includes and indexOf method don't really work as you'd expect on them. So we have this users array here, and this users array, we're declaring it as const. And so it's inferred as a read-only array containing Matt, Sophia and Vakas in that order.

00:18 And then we call users.includes Brian on there. And because Brian is not a member of this array, then it's going to error at us. And same thing here with indexOf. OK, that's a little bit annoying, and this is annoying in a bunch of different ways.

00:34 And really, it's annoying because you want to check whether, let's say, a string conforms to three things that you know already. So let's say you have a bunch of URLs that you can sort of like whitelist against or, you know, allow list against. And then you want to check if the URL that's being passed in and validate it against those.

00:53 This just gets pretty annoying. And there is a way that you can fix this or make this a little bit better, which is using a tool that I've created called Total TypeScript TS Reset. You can import this into your project, import it in one line, and it globally affects some of the types in TypeScript.

01:11 And instead of includes now requiring it to be either Matt or Sophia or Vakas, when we uncomment this, we can see that it is just string. So it sort of defaults to the wider type there.

01:25 This is really useful, and it means that you can kind of use these with a bit more flexibility and just by with a single import. So this is like a really, really useful tool in your tool set. It sometimes makes TypeScript a bit stricter. Sometimes here makes it just a little bit helpfully looser.

01:42 And you might think, why don't the TypeScript team just use TS Reset in their types? Well, I mean, there's an argument to be made that maybe this is the right situation, given that this is, you know, a bunch of users. You can argue this from both sides, I think. But for me, I prefer just having like the wider version of this. And so TS Reset is a really useful tool for that.

02:03 So there we go. So read-only arrays includes and index of can be a little bit annoying. So I recommend using TS Reset to smooth that out.