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);
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:
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;
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.
Here is the typescript playground for you to play around with.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.