25

What is the correct type for 'e' as in uploadImage function parameter?

public uploadImage(e /* :type of e */){
 const image = e.target.files[0];
 const reader = new FileReader();
 reader.readAsDataURL(image);
 reader.onload = e =>{
    this.previewImage = e.target.result;
    console.log(this.previewImage);
 };
}

In template I have this

<input type="file" accept="image/jpeg" @change=uploadImage>
hdk
  • 720
  • 2
  • 9
  • 19

5 Answers5

25

The type is just Event. Relevant information is on e.target property.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
10

You can use your self annotation for this type.

interface InputFileEvent extends Event {
    target: HTMLInputElement;
}

public uploadImage(e: InputFileEvent) {
    const image = e.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(image);
    reader.onload = e =>{
        this.previewImage = e.target.result;
        console.log(this.previewImage);
   };
}
Arsonik
  • 2,276
  • 1
  • 16
  • 24
Глеб
  • 101
  • 1
  • 3
4

Obviously I'm late to the party, but I was rewriting some legacy components. In the end I ran into Typescript errors - the template event didn't like me destructuring directly because the target was EventTarget, not HTMLInputElement or whatever the given element I needed.

So instead of directly destructuring the arguments I just set it afterwards as a variable, using the as keyword.

Example:

foo(event: Event) {
  const el = event.target as HTMLInputElement
  // do stuff
}

I wish I knew some handy trick to destructure it from the arguments directly with the correct type, but alas I haven't been that fortunate.

Drunkenvalley
  • 126
  • 1
  • 2
2

If you give the type as Event, then you will be unable to do e.target.files[0]; as TS will complain that Property 'files' does not exist on type 'target' error in typescript. The simplest solution is to give it type as any referring shusson's solution here: Property 'files' does not exist on type 'EventTarget' error in typescript but even this didn't work for me so I ended up just not using TS for that particular Vue component

Ayudh
  • 1,673
  • 1
  • 22
  • 55
  • 1
    If the type `any` does not even work, you probably tried to make something work that can't work, may it be with or without types. Using `any` is wrong in the first place because by that you disable the advantage of Typescript. If you plan to do that, the better solution is (honestly) to uninstall Typescript. – gekkedev Oct 15 '20 at 16:47
2

There are different type of events and types. For example you can use DragEvent type for drag action : https://developer.mozilla.org/en-US/docs/Web/API/DragEvent.
There is also InputEvent for inputs. : https://developer.mozilla.org/en-US/docs/Web/API/InputEvent.
The Event is more generic. enter image description here

bilgin
  • 133
  • 1
  • 13