typescriptfilelist

TypeScript Property 'forEach' does not exist on type 'FileList'


I enable users to upload multiple files. Then I need to iterate over these files and perform some actions. I wanted to add some extra functionality to FileList but TS does not know forEach on FileList arrays. This is my code:

public uploadMultiple(evt){
    console.log(evt.files);
    FileList.prototype.forEach = function(callback) {[].forEach.call(this, callback)};
}

Solution

  • You need to declare the extra functions on the FileList interface before you can assign it. You can do this using declaration merging. If you are using a module system the merged interface need to be declared in global:

    declare global {
        interface FileList {
            forEach(callback: (f: File) => void) : void;
        }
    }
    FileList.prototype.forEach = function(callback) {  ... };