Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - How to detect key pressed in TypeScript?

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
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use the more specialised event type KeyboardEvent, as shown below:

myFunc(data : string, evt : KeyboardEvent)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...