Filter FileList using TS

I would like to remove the respective image from the array after clicking on a button. If I declare the whole thing as follows, I get the below message or error from TypeScript

const [fileList, setFileList] = useState<FileList | null>(null);

const deleteImage = (image: File) => {
const filteredList: FileList = Array.from(fileList!!).filter(function (img) {
  return img !== image;
});

setFileList(filteredList);

};

Property ‘item’ is missing in type ‘File[]’ but required in type ‘FileList’

>Solution :

The Mozilla reference page for FileList notes that this interface has essentially been deprecated, and recommends that you just use an array of File objects instead.

That’s what you’re doing anyway, ignoring the type declarations – Array#filter returns an array, not a file list. So, you could just change FileList to File[] throughout.

If you really need to preserve compatibility with FileList (for an external API perhaps?) then you’ll need to wrap that array in something that implements the .item(..) accessor. It does not appear that a FileList constructor is available in JavaScript.

Leave a Reply