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

标签 javascript typescript casting

当我运行代码时:

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/

相关文章:

Javascript 库或 jquery 插件,用于在移动 safari/ipad 中创建基于滑动的轮播

javascript - 为什么 JavaScript 这样做?

html - Visual Studio/Chrome 不更新 HTML/Typescript

javascript - 如何使用 'require' 导入命名空间?

c++ - 如何使用其地址作为整数的实际值,正确地将文字整数作为空指针作为参数传递

c# - 在 C# 中转换为字节

javascript - 如何合并和求和 MongoDB 的结果

javascript - 虚拟表自动高度的三元运算符

javascript - 为什么在服务中的函数中使用 let 和 new 创建新对象时会得到旧对象?

c# - 在 C# 中定义泛型类型的显式转换