什么 Typescript 类型是更改事件?(角度)

Rya*_*zel 20 typescript angular

我试图找出在 Angular 项目中使用的更改事件的 Typescript 类型。

代码很简单,如下所示:

文件上传.component.html

<input type="file" (change)="onChange($event)"/>
Run Code Online (Sandbox Code Playgroud)

文件上传.ts

public onChange(event: Event): void {
  if (event.target.files && event.target.files.length) {
    const [file] = event.target.files;
    console.log(file);
  }
}
Run Code Online (Sandbox Code Playgroud)

键入事件为Event我提供了以下 Typescript linting 错误:

public onChange(event: Event): void {
  if (event.target.files && event.target.files.length) {
    const [file] = event.target.files;
    console.log(file);
  }
}
Run Code Online (Sandbox Code Playgroud)

如果没有,我应该输入什么Event

QT *_*Ray 27

这是一个事件。但是您将不得不将您使用的常量转换为 HTMLInputElement。

public onChange(event: Event): void {
  if ((event.target as HTMLInputElement).files && (event.target as HTMLInputElement).files.length) {
    const [file] = event.target.files;
  }
}
Run Code Online (Sandbox Code Playgroud)

唯一的另一种方法是使用 tsignore 抑制错误。在 react、flow 中,它们有一个 SyntheticEvent 类型,您可以输入这个特殊情况来绕过它,但 angular 没有真正的等价物。


Dev*_*evz 13

在对您的活动进行任何操作之前,您只需编写以下内容:

if (!(event.target instanceof HTMLInputElement)) return;
Run Code Online (Sandbox Code Playgroud)

然后 Typescript 就会知道你event.target是 的一个实例HTMLInputElement,并且它会停止对你大喊大叫。


Cha*_*ard 8

您可以使用交集类型作为 的类型提示来指定target的属性。EventHTMLInputElementevent

public onChange(event: Event & { target: HTMLInputElement }): void {
  if (event.target.files && event.target.files.length) {
    const [file] = event.target.files;
    console.log(file);
  }
}
Run Code Online (Sandbox Code Playgroud)

交叉类型将多种类型合并为一种。这允许您将现有类型添加在一起以获得具有您需要的所有功能的单一类型。

https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types

  • 不错的技巧,但在这里你会在 html 模板中遇到编译错误: Argument of type 'Event' is not allocate to argument of type 'Event &amp; { target: HTMLInputElement; }'。 (4认同)

Fir*_*iki 6

如果你是React用户的Typescript并且像我一样登陆这个线程,这对你有用:

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { 
   // do something 
}
Run Code Online (Sandbox Code Playgroud)


nki*_*tku 5

public onChange(event: Event): void {
    const input = event.target as HTMLInputElement;

    if (!input.files?.length) {
        return;
    }

    const file = input.files[0];
    console.log(file);
}
Run Code Online (Sandbox Code Playgroud)


Eli*_*hle 5

接受的答案在我的编译器中抛出两个错误:(event.target as HTMLInputElement).files is possibly 'null'Type 'FileList' must have a '[Symbol.iterator]()' method that returns an iterator

这对我有用:

const target = event.target as HTMLInputElement;

if (target.files && target.files.length) {
  const file = target.files[0];
}
Run Code Online (Sandbox Code Playgroud)