Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
Alwyn Avatar asked Jun 08 '14 16:06

Alwyn


2 Answers

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;
}
like image 138
Fenton Avatar answered Oct 19 '22 03:10

Fenton


For React Users

  private onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
    console.log(e.key)
  }

where HTMLDivElement is the type of whichever element onKeyDown is attached to.

Here is the List (from line 32-90) of all supported HTML elements.

like image 35
Damian Green Avatar answered Oct 19 '22 02:10

Damian Green