当我运行代码时:
public onResize(event: Event) {
console.log(event.target.innerWidth);
//--solution--
//var w = event.target as Window;
//console.log(w.innerWidth);
}
我收到一个错误:
Property innerWidth does not exist on type EventTarget
我想避免在 TypeScript 中扩展类型(如此处所述 Property 'value' does not exist on type 'EventTarget' ),所以我将 event.target
转换为 Window
类。我不确定我是否投到了合适的类(class)。我应该投到哪个类(class)?如何找到应该转换到的合适类?
最佳答案
调整大小事件使用 UIEvent 接口(interface)。
https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event
UIEvent 有一个 target 属性,不幸的是,它没有“innerWidth”属性。因此,相反,我们断言事件的目标为窗口
即
window.addEventListener('resize', (event: UIEvent) => {
const w = event.target as Window;
console.log(w.innerWidth) // works!
});
关于javascript - EventTarget 类型上不存在属性 innerWidth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955307/