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.

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

Top comments (0)

Image of PulumiUP 2025

Explore What’s Next in DevOps, IaC, and Security

Join us for demos, and learn trends, best practices, and lessons learned in Platform Engineering & DevOps, Cloud and IaC, and Security.

Save Your Spot

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay