'What is the type for an event in Vue TypeScript project?
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>
Solution 1:[1]
The type is just Event. Relevant information is on e.target property.
Solution 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
Solution 3:[3]
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.

Solution 4:[4]
You can use your self annotation for this type.
interface InputFileEvent {
target: {
files: Array</* you can specify here fields that need you or all of them */>
}
}
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);
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Radu Diță |
| Solution 2 | |
| Solution 3 | bilgin |
| Solution 4 | Глеб |
