简体   繁体   中英

Typescript - Loop through an array backwards with noUncheckedIndexedAccess enabled

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'.

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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM