什么 Typescript 类型是更改事件?(角度) [英] What Typescript type is a change event? (In Angular)
问题描述
我正在尝试找出 Angular 项目中使用的更改事件的 Typescript 类型.
I'm trying to figure out what Typescript type a change event is used in an Angular project.
代码很简单:
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);
}
}
将事件输入为 Event
会给我以下 Typescript linting 错误:
Typing the event as Event
gives me the following Typescript linting error:
Property 'files' does not exist on type 'EventTarget'
如果不是Event
,我应该输入什么?
What should I be typing this if not Event
?
推荐答案
这是一个事件.但是您将不得不将您使用的常量转换为 HTMLInputElement.
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;
}
}
唯一的另一种方法是使用 tsignore 抑制错误.在 react 和 flow 中,它们有一个 SyntheticEvent 类型,您可以输入这个特殊情况来绕过它,但 angular 没有真正的等价物.
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.
这篇关于什么 Typescript 类型是更改事件?(角度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!