Javascript 你如何在Typescript中找到事件的类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35820248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:15:33  来源:igfitidea点击:

How do you find the type of event in Typescript

javascripteventstypescriptangular

提问by Kevin

Here is my template

这是我的模板

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

Here is my typescript file

这是我的打字稿文件

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

The console.logoutputs objectbut in reality it should be KeyboardEvent.

console.log输出object但在现实中它应该是KeyboardEvent

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

有没有通用的方法来查找事件的类型?

回答by Aaron Beall

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

您可能只想检查event.type以查看它是什么,并从中推断出类型。

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

否则,您可以尝试使用event instanceof KeyboardEvent用户定义的类型保护

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

此外,在您的示例中,您可以只使用参数event:KeyboardEvent而不是event:any.