怎样告诉 TypeScript 一劳永逸地,ResizeObserver 不总是存在于 window 上?

huangapple go评论71阅读模式
英文:

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

问题

我正在使用带有特征检测的 ResizeObserver,如下所示:

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

这会导致 TypeScript 错误 "TS2339: Property 'removeEventListener' does not exist on type 'never'"。

我可以逐个解决这个问题,要么通过使用 ts-ignore 注释,要么通过 window as Partial<Window>。但是,我想知道是否可以告诉 TypeScript 一劳永逸地,ResizeObserver 不总是存在,因为它不受较旧的 Safari 版本支持。

英文:

I am using ResizeObserver with feature detection like this:

if (&quot;ResizeObserver&quot; in window) {
    // Use ResizeObserver
} else {
    window.addEventListener(&quot;resize&quot;, 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&lt;Window&gt;. 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.

答案1

得分: 2

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

英文:

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

interface Window {
    ResizeObserver?: ResizeObserver;
}

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

Playground

huangapple
  • 本文由 发表于 2023年2月24日 00:04:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定