3

I've started to rewrite some of my Javascript code in Typescript to learn how Typescript works. However I'm at a point where the Type annotations make some trouble.

I try to get a file from an input field, in Javascript I do

var file = document.getElementById('upload_files').files[0];

what I now try to write in typescript but I can't figure out, how I've to cast to access the .files property in Typescript.

Nitro.de
  • 821
  • 10
  • 27

1 Answers1

4

Figured it out..

I had to cast the element to a HTMLInputElement thats where the files property is included.

var fileElement = <HTMLInputElement>document.getElementById('upload_files');
var file = fileElement.files[0];
Nitro.de
  • 821
  • 10
  • 27
  • 1
    Even better, you should use `document.getElementById('upload_files') as HTMLInputElement`, as this is the preferred syntax for type _assertions_ (not type _casting_). – John Weisz Apr 06 '16 at 08:26
  • See [this answer](https://stackoverflow.com/a/43176930/23118) for a HTMLInputEvent type. – hlovdal Apr 26 '18 at 13:42