您如何在打字稿中找到事件的类型? [英] How do you find the type of event in Typescript?

查看:62
本文介绍了您如何在打字稿中找到事件的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的HTML模板:

Here is my HTML template:

<input (keyup)="onKey($event)">

这是我的TypeScript文件:

Here is my TypeScript file:

onKey(event: any) {
    console.log(typeof event);
}

console.log 输出 object ,但实际上它应该是 KeyboardEvent .

The console.log outputs object but in reality it should be KeyboardEvent.

是否存在一种通用的方法来查找事件的类型?

Is there a generic way to find the type of event?

推荐答案

您可能只想检查 event.type 来查看其内容,然后从中推断出类型.

You probably want to just check the event.type to see what it is, and infer the type from that.

否则,您可以尝试使用 KeyboardEvent的事件实例

Otherwise you could try using event instanceof KeyboardEvent or user-defined type guards.

此外,在您的示例中,您只需将参数 event:KeyboardEvent 而不是 event:any .

Also, in your example you can just make the argument event:KeyboardEvent instead of event:any.

这篇关于您如何在打字稿中找到事件的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆