Typescript not allowing the use of the files property

0

I have a problem with ionic, in which I use the .files property in an id of a <input type="file"> element, like this:

<input type="file" id="images" multiple>
this.register.images = document.getElementById('images').files;

And it works, this.register.images is populated with files uploaded in input however, the Text Editor I use (Visual Studio Code) points to the following error:

What,inturn,whenIbuildtheionic,itgivesmeacompileerror:

Andso,Icannotcontinuedevelopingtheapplication,so:

  • Isthereanywayforthiserrortoaddup?
  • Orsomeotherwaytogetfilesfrom<inputtype="file"> ?
asked by anonymous 18.06.2018 / 15:35

1 answer

0

This is not an error, which is that the document.getElementById method returns something of type HTMLElement | null , so you have to check the instance of your element.

let element: HTMLElement | null = document.getElementById('images');
if ( element instanceof HTMLInputElement ) {
    this.register.images = element.files
}

This is because TypeScript has no way of knowing the type of element that will be present in the DOM, so it returns the interface that satisfies the need of any element (span, div, p, etc ...)

    
18.06.2018 / 22:33