如何检测TypeScript中按下的键? [英] How to detect key pressed in TypeScript?
问题描述
打字稿中与javascript中的以下行在语义上等效的语法是什么
What would be the semantically equivalent syntax in typescript to the following line in javascript
//Some knockout event handler.
myFunc(data : string, evt : Event) {
//If enter or tab key up were detected add the excuse to the collection.
if(evt.enterKey || evt.which == 9)
//Do Something
}
我在这里遇到的麻烦与常规的 javascript 事件不同,typescript 事件类没有属性 enterKey
或 which
.那么如何在不出现打字稿编译错误和丑陋的红色摆动下划线的情况下检测正在按下哪个键?
The trouble I'm having here is unlike regular javascript event, typescript Event class does not have a property enterKey
or which
. So how do I detect which key is being pressed without getting typescript compile error and the ugly red wiggly underline?
推荐答案
需要使用更专业的事件类型KeyboardEvent
,如下图:
You need to use the more specialised event type KeyboardEvent
, as shown below:
myFunc(data : string, evt : KeyboardEvent)
如果您还想删除 evt.enterKey
的错误,您需要通过扩展接口来添加它 - 尽管我不知道这是一个真实的属性,因为它不是技术上的控制键,例如 CTRL
、SHIFT
或 ALT
,它们都具有事件属性:
If you want to also remove errors for evt.enterKey
you'll need to add it by extending the interface - although I'm not aware that this is a real property as it isn't technical a control key, like CTRL
, SHIFT
or ALT
, which all have properties on the event:
interface KeyboardEvent {
enterKey: boolean;
}
这篇关于如何检测TypeScript中按下的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!