Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I tell typescript once and for all that ResizeObserver is not always present on window?

I am using ResizeObserver with feature detection like this:

if ("ResizeObserver" in window) {
    // Use ResizeObserver
} else {
    window.addEventListener("resize", doFallBack(), {passive: true});
}

This gives a typescript error "TS2339: Property ‘removeEventListener’ does not exist on type ‘never’".

I can solve this on a case by case basis, either with a ts-ignore comment or with window as Partial<Window>. However, I am wondering if I can tell typescript once and for all that ResizeObserver is not always present, since it isn’t supported by older Safari versions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can augment the Window interface and say that ResizeObserver should be optional:

interface Window {
    ResizeObserver?: ResizeObserver;
}

if ("ResizeObserver" in window) {
    // Use ResizeObserver
} else {
    window.addEventListener("resize", doFallBack(), {passive: true});
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading