相关文章推荐
谦逊的硬币  ·  react ...·  1 周前    · 
越狱的鼠标  ·  eslint - ...·  7 小时前    · 
魁梧的板凳  ·  c# ...·  7 月前    · 
苦恼的鸡蛋面  ·  r语言画直线-掘金·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

If there is something that accomplishes the above, for typescript, then it is an alternative – TopBanana9000 Jul 29, 2016 at 13:54 Can you explain a bit more about the environment? Are you compiling the code to run on a browser or interpreting somewhere? – Ismael Miguel Jul 29, 2016 at 13:55

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
                There is no need for this if your project is setup correctly.  lib.d.ts defines window with an onkeydown property.
– AlexG
                Jul 29, 2016 at 14:06
                Get Type '(event: React.KeyboardEvent<Element>) => void' is not assignable to type 'EventListener'.
– Tunn
                Feb 13, 2020 at 0:18
                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, 2020 at 9:57
windows.addEventListener('keydown', (event: KeyboardEvent) =>{
 // if you need event.code
windows.addEventListener('keydown', (event: Event) =>{
 // event
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.