Home > Back-end >  Typescript - Loop through an array backwards with noUncheckedIndexedAccess enabled
Typescript - Loop through an array backwards with noUncheckedIndexedAccess enabled

Time:11-06

What is the best way to loop through an array backwards in TypeScript, with strict and noUncheckedIndexedAccess options enabled? The most classic approach no longer works well in this config:

function doSomething(i: number): void {
  ...
}

const arr = [1, 2, 3];
for (let i = arr.length - 1; i >= 0; --i) {
  doSomething(arr[i]);
}

It fails with a compilation error:

Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
  Type 'undefined' is not assignable to type 'number'.

CodePudding user response:

noUncheckedIndexedAccess is primarily useful for objects, and for arrays if the index you're looking up might be more than the length of the array.

If you can be absolutely certain that the value exists at the index specified - such as with dead-simple code like this (assuming you don't mutate the array inside the function) - then simply assert that the value exists before passing it around:

for (let i = arr.length - 1; i >= 0; --i) {
  doSomething(arr[i]!);
}

Another option would be to reverse the array, then iterate over it, which is a bit more computationally expensive, but easier to make sense of at a glance.

arr.reverse().forEach(doSomething);
// no mutation:
[...arr].reverse().forEach(doSomething);
// no mutation:
for (const item of [...arr].reverse()) {
    doSomething(item);
}

Those last three are what I'd prefer over a for loop when feasible.

CodePudding user response:

Why you didn't do it as anyone else

arr.map(dosonething);

Buy if you still want to do it as you Is add an if

if (art[I]!==undefined){
dosonething(art[I]);
  • Related