Normally when we want to catch an event on a page in js:

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

How to make it in Typescript ?

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;

Also, in Typescript, we can handle it like this:

const controlDown = (event: KeyboardEvent) => {
    console.log(event);
};
window.addEventListener('keydown', controlDown);

or this, if we want to keep our original “style” :

window.onkeydown = (ev: KeyboardEvent): any => {
     //do something
}

Be Aware !!

Even when TypeScript is playing by JavaScript rules, however, there are limits to what the compiler will allow. Let’s try adjusting onClick to expect a number:

const onClick = (n: number) => { /* ... */ }

window.addEventListener('click', onClick);

This time, we’ll see the expected compiler error:

// Argument of type '(e: number) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
//   Type '(e: number) => void' is not assignable to type 'EventListenerObject'.
//     Property 'handleEvent' is missing in type '(e: number) => void'.

As one would expect, ‘click” or  keydown" will spawn a Mousevent or KeyboardEvent – not a number.

So the right way to write the function onClick would be :

const onClick = (e: MouseEvent) =>
  console.log(`(${e.clientX}, ${e.clientY})`);

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *