Configuring TypeScript 16 exercises

Making Code Safer with No Unchecked Indexed Access

The danger with having the type inferred as number is that we might try to access an index that doesn't exist. For example, we might try to access the fourth element of the array, even though it only contains three elements:

const array = [1, 2, 3];
const mightNotExist = array[3];

Loading solution


00:00 Okay, so the danger is here that we might access something that we expect to be a number and in fact It's undefined and we would get a runtime error off that so we need to change our TS config.json file And we need to add back no unchecked indexed access true

00:18 And now when we add that back in then if we look at index.ts might not exist is now number or Undefined look at that if there was a string inside here like this, then we would get string or number or undefined Okay, very interesting typescript is making our code a little bit safer here

00:38 This works for arrays, but it also works for objects, too Now this does have some upsides and downsides You're going to get more errors out of this and so you might end up if you happen to know that might not exist does Exist and you need to do like to exponential like this

00:54 You might need to do some more non null asserting here just to make sure that you yes I really do know it exists But of course you could say if might not exist and then you can say might not exist up to exponential for instance So you can do some narrowing too. So it is going to

01:11 Bug you a little bit and annoy you in certain places, but then you know, this is typescript, right? That's kind of its job and so no unchecked index access is always something that I recommend setting to true at the beginning of a project and It just catches more errors for you and means that your code is a little bit safer