19

Normally when I wanted to catch an event on a page in js:

window.onkeydown = function (event) {
    //Do something here
}

I cannot seem to figure out (or Google) how to do this in typescript. For the setup I am working in, there is a ts file for the page, and a ts file for the class that it is loading.

TopBanana9000
  • 818
  • 2
  • 14
  • 32

3 Answers3

24

This

window.addEventListener('keydown', keyDownListener, false)

window is defined will all events in lib.d.ts and this particular listener as

 addEventListener(type: "keydown", listener: (ev: KeyboardEvent) => any, useCapture?: boolean): void;

or this, if you want to keep your original "style",

window.onkeydown = (ev: KeyboardEvent): any => {
     //do something
}
Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
  • 1
    There is no need for this if your project is setup correctly. lib.d.ts defines window with an onkeydown property. – AlexG Jul 29 '16 at 14:06
3

To answer more clearly:

const controlDown = (event: KeyboardEvent) => {
    console.log(event);
};
window.addEventListener('keydown', controlDown);
manu
  • 1,059
  • 1
  • 16
  • 33
  • 6
    Get `Type '(event: React.KeyboardEvent) => void' is not assignable to type 'EventListener'.` – Tunn Feb 13 '20 at 00:18
  • 28
    In case of using this with React make sure you don't accidentally use `import { KeyboardEvent } from "react";`. This leads to the `not assignable to type 'EventListener'` exception. Instead the KeyboardEvent from globalThis must be used (i.e. simply remove the import statement) – luk Aug 14 '20 at 09:57
2
windows.addEventListener('keydown', (event: KeyboardEvent) =>{
 // if you need event.code
});

windows.addEventListener('keydown', (event: Event) =>{
 // event
});