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

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


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];


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


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 **/};