13

When I run a code:

public onResize(event: Event) {
    console.log(event.target.innerWidth);

    //--solution--
    //var w = event.target as Window;
    //console.log(w.innerWidth);
  }

I receive an error:

Property innerWidth does not exist on type EventTarget

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?

ael
  • 514
  • 9
  • 26

2 Answers2

25
  1. A resize event uses the UIEvent Interface.

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

  2. A UIEvent has a target property which, unfortunately, has no "innerWidth" property. So, instead, we assert the target of the event as Window

i.e.

window.addEventListener('resize', (event: UIEvent) => {
  const w = event.target as Window; 
  console.log(w.innerWidth) // works!
});
Community
  • 1
  • 1
Brandon
  • 1,747
  • 2
  • 13
  • 22
1

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.

Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75
  • 1
    I know an element I registered the event listener on, but I don't know a type of the element. For example let's assume it is `` : if I register event listener on a canvas, how to find out the type of that element? Is it `Canvas` or `HTMLCanvasElement`, or maybe none of them? Is anywhere any documentation which describes JavaScript classes? I have been looking for it on ( https://developer.mozilla.org ) but I couldn't find. – ael Aug 21 '18 at 19:42
  • 1
    For , if you look at the documentation [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas), the "DOM interface" is `HTMLCanvasElement`, and that should generally be the name to use in TypeScript too. – Matt McCutchen Aug 21 '18 at 19:50