类型EventTarget上不存在属性innerWidth [英] Property innerWidth does not exist on type EventTarget

查看:149
本文介绍了类型EventTarget上不存在属性innerWidth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行代码时:

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中扩展类型(如此处所述

I would like to avoid extending types in TypeScript (as it is described here Property 'value' does not exist on type 'EventTarget' ), so I cast event.target to Window class. I'm not sure if I cast to proper class. Which class should I cast to? How to find out a proper class which should be cast to?

推荐答案

如果知道在哪个元素上注册了事件侦听器,则可以将 event.target 强制转换为该元素类型.我认为没有什么比这更多的了.另外,您可以直接引用在其上注册了侦听器的元素(在这种情况下,仅是全局 window ),而不是使用 event.target .

If you know what element you registered the event listener on, then you could cast event.target to that element type. I don't think there's any more to say than that. Alternatively, you can directly reference the element you registered the listener on (in this case just the global window) rather than using event.target.

这篇关于类型EventTarget上不存在属性innerWidth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆