Home > other >  An Uint8Array is being cast into a String when Placed in a For Loop in typescript
An Uint8Array is being cast into a String when Placed in a For Loop in typescript

Time:07-27

I am looping over an Array of Uint8Array in TypeScript, but I get an error in Visual Studio that each specific Uint8Array is actually a string and it fails the typeCheck. I'm not sure why this is happening.

function failState (arrayOfUint8Array: Array<Uint8Array>){

    for (const specificUint8Array in arrayOfUint8Array){

         functionRequiringUint8Array(specificUint8Array)

        //specificUint8Array is a String and can't be used in function
        

    }
}

CodePudding user response:

You probably want to use a for-of instead of a for-in loop.

The main difference between a for-in loop and a for-of loop is that a for-in loop iterates of the own enumerable properties of the object that's passed in.

In case of an array it will return numbers from 0 to Array.length - 1 - the indices of the array.

const arr: string[] = ["Mike", "Pete", "Jack"];
for(const key in arr){
  console.log(key); // prints "0", "1", "2".
}

A for-of loop on the other hand iterates over iterable objects or user-defined iterables.

const arr: string[] = ["Mike", "Pete", "Jack"];
for(const name of arr){
  console.log(name); // prints "Mike", "Pete", "Jack".
}
  • Related