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

一曲冷凌霜 提交于 2019-11-28 00:38:50

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]; 
    //...
}

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...
}

This is more lines, but I think it's the clearest.

const onChange = (event: Event) => {
  const target= event.target as HTMLInputElement;
  const file: File = (target.files as FileList)[0];
  /** do something with the file **/
};

The simplest solution is to declare e as any

e.g

document.getElementById('customimage').onchange = (e: any) => {
    let files = e.target.files[0];
    ...
};

But you lose type information. A safer approach might be to declare your own FileEvent type based on https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload.

Tiaan Oosthuizen

I have found that:

<input type="file"  accept="image/*" 
(change)="upload($event)">

and

<ion-input type="file"  accept="image/*" 
(change)="upload($event)"><ion-input>  or (ionChange)

does not handle the event in the same way. Therefore event.target consists of different parameters.

I therefore did not use the ion-input tag, but the normal angular <input> tag with the (change)="upload($event)" trigger.

It worked for me on Ionic 4.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!