Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the TS type of HTMLInputElement.files property may be null?

There is input with type='file' attribute like this:

function TestComp() {
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const [file] = e.target.files;
    //...
  };

  return <input type='file' onChange={onChange}/>
}

Got error:

type ‘FileList | null’ must have a ‘Symbol.iterator’ method that returns an iterator.ts(2488)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The e.target.files TS type is:

interface HTMLInputElement extends HTMLElement { 
  /**
   * Returns a FileList object on a file type input object.
   */
  files: FileList | null;
}

In what scenario, the e.target.files may be null?

>Solution :

That’s the behaviour of HTMLFileElement, it returns null for files if the type is not set to file.

const fileInput  = document.createElement('input');
fileInput.files // null 

fileInput.type = "file"
fileInput.files // FileList
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading