Search code examples
typescriptfilelist

For In loop with Filelist returns the wrong type


I'd like to loop through a FileList with a for in loop, using Typescript. I started out with a regular old for loop, and this works perfectly:

let files:FileList = e.target.files
for(let i = 0;i<files.length;i++){
  doSomething(files[i])
}

function doSomething(f:File){
}

But when I use the shorter for..in loop:

for(let f in files){
   doSomething(f) 
}

I get an error: Argument of type 'string' is not assignable to parameter of type 'File'. So f is somehow deemed a string, even though a FileList contains Files, not strings.

These fixes don't work:

for(let f:File in files){ // left hand assignment not allowed
    doSomething(f as File) // cannot convert string to File
} 

Is this just not possible?


Solution

  • You cannot iterate using

    for(let f in files){
       doSomething(f) 
    }
    

    A FileList is not an Array, but it does conform to its contract (has length and numeric indices), so we can "borrow" Array methods:

    you have to iterate as you are doing based on length.

    You have to follow this syntax

    for(let i = 0;i<files.length;i++){
      doSomething(files[i])
    }
    

    Refers to api

    https://developer.mozilla.org/en-US/docs/Web/API/FileList