Issue
I'm trying to figure out what Typescript type a change event is used in an Angular project.
The code is something simple like this:
file-upload.component.html
<input type="file" (change)="onChange($event)"/>
file-upload.ts
public onChange(event: Event): void {
if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
console.log(file);
}
}
Typing the event as Event
gives me the following Typescript linting error:
Property 'files' does not exist on type 'EventTarget'
What should I be typing this if not Event
?
Solution
It is an event. But you're going to have to cast the const you're using as an HTMLInputElement.
public onChange(event: Event): void {
if ((event.target as HTMLInputElement).files && (event.target as HTMLInputElement).files.length) {
const [file] = event.target.files;
}
}
The only other way is going to be to suppress the error with tsignore. In react, flow, they have a type SyntheticEvent that you can type this particular case as to get around it but angular doesn't have a real equivalent.
Answered By - QT Ray
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.