Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert FileList to Array using Array.from and spread syntax in typescript

This line const files = Array.from(e.target.files); produces an error in typescript.

I'm a newbie to typescript. It appears the object is not an array-like, but it actually is. What can I do to fix this?

The error is:

"No overload matches this call. Overload 1 of 4, '(iterable: Iterable | ArrayLike): File[]', gave the following error. Argument of type 'FileList | null' is not assignable to parameter of type 'Iterable | ArrayLike'. Type 'null' is not assignable to type 'Iterable | ArrayLike'. Overload 2 of 4, '(arrayLike: ArrayLike): File[]', gave the following error. Argument of type 'FileList | null' is not assignable to parameter of type 'ArrayLike'. Type 'null' is not assignable to type 'ArrayLike'."

Here's the code:

import { ChangeEvent } from 'react';
import './styles.css';

export function App() {
  const handleFileLoad = function (e: ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files);
    // I want to use forEach here, so I attempt to convert it to an array.
  };

  return (
    <div>
      <input type="file" onChange={handleFileLoad} />
    </div>
  );
}
like image 300
twentysixhugs Avatar asked Aug 30 '26 15:08

twentysixhugs


2 Answers

The reason why you're getting an error is because files in e.target.files might be null, which can cause Array.from(e.target.files) to error out, so TypeScript is sort of prompting you to provide a fall-back for that scenario.

like image 131
Michael Colesnic Avatar answered Sep 01 '26 06:09

Michael Colesnic


I found the answer. This will do the job:

const files = Array.from(e.target.files as ArrayLike<File>);

We can consider FileList to be an ArrayLike that contains elements

For some reason, typescript didn't manage to guess it on its own.

like image 35
twentysixhugs Avatar answered Sep 01 '26 04:09

twentysixhugs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!