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

后端 未结 7 685
迷失自我
迷失自我 2020-11-30 09:50

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

相关标签:
7条回答
  • 2020-11-30 10:04

    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.

    0 讨论(0)
  • 2020-11-30 10:08

    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 **/
    };
    
    0 讨论(0)
  • 2020-11-30 10:09
    // use - ChangeEvent<HTMLInputElement>
    
    document.getElementById("customimage").onchange= function(e?: ChangeEvent<HTMLInputElement>) {
                var files: any = e.target.files[0]; 
                  EXIF.getData(e.target.files[0], function() {
                      alert(EXIF.getTag(this,"GPSLatitude"));
                  });
              }
    
    0 讨论(0)
  • 2020-11-30 10:16

    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];
    
    0 讨论(0)
  • 2020-11-30 10:22

    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]; 
        //...
    }
    
    0 讨论(0)
  • 2020-11-30 10:24
    const handleFileInput = (event: ChangeEvent) => {
            const target = event.target as HTMLInputElement;
            const file: File = (target.files as FileList)[0];
            /** do something with the file **/
        };
    

    I would change Event to ChangeEvent, however the rest of Devin Clark's answer is great :)

    0 讨论(0)
提交回复
热议问题