Javascript Typescript键盘事件:参数类型为';事件';不可分配给类型为';键盘事件';
即使代码运行正常,我也会出现以下错误:Javascript Typescript键盘事件:参数类型为';事件';不可分配给类型为';键盘事件';,javascript,typescript,casting,type-conversion,Javascript,Typescript,Casting,Type Conversion,即使代码运行正常,我也会出现以下错误: "TS2345: Argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'. Property 'altKey' is missing in type 'Event'." // In a Class public listenTo = (window: Window) => { ['keydown', 'keyup'].forEach(
"TS2345: Argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'.
Property 'altKey' is missing in type 'Event'."
// In a Class
public listenTo = (window: Window) => {
['keydown', 'keyup'].forEach(eventName => {
window.addEventListener(eventName, e => {
this.handleEvent(e); // <- error here
});
});
}
public handleEvent = (event: KeyboardEvent) => {
const { key } = event;
//...
}
“TS2345:类型为'Event'的参数不能分配给类型为'KeyboardEvent'的参数。
类型“事件”中缺少属性“altKey”。“
//在课堂上
public listenTo=(窗口:窗口)=>{
['keydown','keydup'].forEach(eventName=>{
addEventListener(事件名称,e=>{
本手册(e);//{
const{key}=事件;
//...
}
我试图将事件类型定义为KeyboardEvent,但出现以下错误:
window.addEventListener(eventName, (e:KeyboardEvent) => {
this.handleEvent(e); // <- error here
});
TS2345: Argument of type '(event: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(event: KeyboardEvent) => void' is not assignable to type 'EventListenerObject'.
Property 'handleEvent' is missing in type '(event: KeyboardEvent) => void'.
window.addEventListener(eventName,(e:KeyboardEvent)=>{
这个.handleEvent(e);//类型脚本不能在这里进行完全跳跃,因为它只知道事件名称将是一个字符串,所以使用最通用的事件类型
下面的示例转换为一个独立运行的示例-所以我在演示中使用了“类外”的内容
当字符串是keydown
和keydup
时,您可以保证类型安全,并否决编译器:
let listenTo = (window: Window) => {
['keydown', 'keyup'].forEach(eventName => {
window.addEventListener(eventName, e => {
handleEvent(<any>e);
});
});
}
let handleEvent = (event: KeyboardEvent) => {
const { key } = event;
//...
}
因此,您可以更强烈地键入数组以获得正确的类型:
type KeyboardEventNames = 'keydown' | 'keyup';
let listenTo = (window: Window) => {
const eventNames: KeyboardEventNames[] = ['keydown', 'keyup'];
eventNames.forEach(eventName => {
window.addEventListener(eventName, e => {
handleEvent(e);
});
});
}
let handleEvent = (event: KeyboardEvent) => {
const { key } = event;
//...
}
在最后一个示例中,我们将数组中的元素类型重新定义为仅键盘事件名称,因此编译器现在知道它不处理任何旧字符串,并且可以推断事件类型。字符串'keyup'
和'keydown'
已经是已知的字符串文字类型。但是,代码中的字符串不是candi检查已知字符串文字类型的日期,除非它们是const
public listenTo = (window: Window) => {
['keydown' as const, 'keyup' as const].forEach(eventName => {
window.addEventListener(eventName, e => {
this.handleEvent(e);
});
});
}
或
取决于你的口味
public listenTo = (window: Window) => {
['keydown' as const, 'keyup' as const].forEach(eventName => {
window.addEventListener(eventName, e => {
this.handleEvent(e);
});
});
}
public listenTo = (window: Window) => {
(['keydown', 'keyup'] as const).forEach(eventName => {
window.addEventListener(eventName, e => {
this.handleEvent(e);
});
});
}