DEV Community

TusharShahi
TusharShahi

Posted on

2

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[]> = {};

obj.nonExistentKey.push(2);
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:

arr[15]=2;
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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️