Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'files' does not exist on type 'EventTarget' error in typescript

I am trying to access the value of the input file from my ionic 2 application but still I'm facing the issue of property files does not exist on type 'EventTarget'. As it is properly working in js but not in typescript. The code is given below:

  document.getElementById("customimage").onchange= function(e?) {             var files: any = e.target.files[0];                EXIF.getData(e.target.files[0], function() {                   alert(EXIF.getTag(this,"GPSLatitude"));               });           } 

Please help me solve this issue as it is not building my ionic 2 application.

like image 420
Chirag Chaudhari Avatar asked Apr 03 '17 04:04

Chirag Chaudhari


People also ask

How do you type an event target in TypeScript?

Use a type assertion to type event. target in TypeScript, e.g. const target = event. target as HTMLInputElement . Once typed correctly, you can access any element-specific properties on the target variable.

What is EventTarget?

The EventTarget interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.

What is event target value in Javascript?

The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.


2 Answers

You can cast it as a HTMLInputElement:

document.getElementById("customimage").onchange = function(e: Event) {     let file = (<HTMLInputElement>e.target).files[0];     // rest of your code... } 

Update:

You can also use this:

let file = (e.target as HTMLInputElement).files[0]; 
like image 124
soroush gholamzadeh Avatar answered Sep 29 '22 15:09

soroush gholamzadeh


The e.target property type depends on the element you are returning on getElementById(...). files is a property of input element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

In this case, the TypeScript compiler doesn't know you are returning an input element and we dont have an Event class specific for this. So, you can create one like the following code:

interface HTMLInputEvent extends Event {     target: HTMLInputElement & EventTarget; }  document.getElementById("customimage").onchange = function(e?: HTMLInputEvent) {     let files: any = e.target.files[0];      //... } 
like image 41
Diullei Avatar answered Sep 29 '22 16:09

Diullei