DEV Community


Posted on

TypeScript Tip #1: forEach vs for loop

While working on a typescript project, it is recommended to enable noUncheckedIndexedAccess for safer object access.

The difference it makes can be summarised below:

const obj : Record<string,number[]> = {};

Enter fullscreen mode Exit fullscreen mode

Without enabling the flag the above will not throw an error. Above is a trivial example but I hope it shows the importance of this flag.

Enabling this flag leads to another hurdle though:

Code image

The error says: Type 'undefined' is not assignable to type 'number'

arr[i] is inferred as undefined inside the for loop. Why though?

Because the length of the above array can be changed like this:

Enter fullscreen mode Exit fullscreen mode

Now, arr.length is 16. The array is sparse and has "holes" or "empty slots" in it. Accessing these elements will give undefined. Hence TypeScript complains.

So how to fix it?

We can use an array method like forEach. Looking at the documentation:

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Code Image

Here is the typescript playground for you to play around with.

Top comments (0)