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
?
Angular includes $event that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object. A component should define the onShow(event) method where the type of the parameter can be KeyboardEvent, MouseEvent, etc.
Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent .
To type the onChange event of an element in React, set its type to React. ChangeEvent<HTMLInputElement> . The ChangeEvent type has a target property which refers to the element. The element's value can be accessed on event.
OnChangeslinkA lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes. interface OnChanges { ngOnChanges(changes: SimpleChanges): void }
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.
public onChange(event: Event): void {
const input = event.target as HTMLInputElement;
if (!input.files?.length) {
return;
}
const file = input.files[0];
console.log(file);
}
You just have to write this before doing anything with your event:
if (!(event.target instanceof HTMLInputElement)) return;
Typescript will then know that your event.target
is an instance of HTMLInputElement
and it will stop yelling at you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With