英文:
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 ("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.
答案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 });
}
英文:
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});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论