如何检测在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 Event类没有属性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屋!