typescript 将 window.event 处理程序添加到打字稿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38660518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:42:05  来源:igfitidea点击:

Adding window.event handler to typescript

javascripttypescript

提问by TopBanana9000

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

通常,当我想在 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 tsfile for the page, and a tsfile for the class that it is loading.

我似乎无法弄清楚(或谷歌)如何在打字稿中做到这一点。对于我正在使用的设置,ts页面有一个ts文件,它正在加载的类有一个文件。

回答by Bruno Grieder

This

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

windowis defined will all events in lib.d.tsand this particular listener as

window将所有事件lib.d.ts和此特定侦听器定义为

 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
}

回答by manu

To answer more clearly:

更清楚地回答:

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