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
How do you find the type of event in Typescript
提问by Kevin
Here is my template
这是我的模板
<input (keyup)="onKey($event)">
Here is my typescript file
这是我的打字稿文件
onKey(event:any) {
console.log(typeof event);
}
The console.log
outputs object
but 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.type
to see what it is, and infer the type from that.
您可能只想检查event.type
以查看它是什么,并从中推断出类型。
Otherwise you could try using event instanceof KeyboardEvent
or user-defined type guards.
否则,您可以尝试使用event instanceof KeyboardEvent
或用户定义的类型保护。
Also, in your example you can just make the argument event:KeyboardEvent
instead of event:any
.
此外,在您的示例中,您可以只使用参数event:KeyboardEvent
而不是event:any
.