gpt4 book ai didi

javascript - EventTarget 类型上不存在属性 innerWidth

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:42 24 4
gpt4 key购买 nike

当我运行代码时:

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)?如何找到应该转换到的合适类?

最佳答案

  1. 调整大小事件使用 UIEvent 接口(interface)。

    https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

  2. 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com