How to detect key pressed in TypeScript?
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.
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;
}
You need register the event, for example:
class EventHandler {
static RegisterKeyPress(input: string){
document.getElementById(input).addListener('keypress', (e: KeyboardEvent) =>{
//You have yout key code here
console.log(e.keyCode);
}
}
}
Happy coding!