You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14.1.1 PWA报错:ServiceWorkerRegistration不存在sync属性

解决Angular 14.1.1 PWA中ServiceWorkerRegistration无sync属性的TypeScript错误

这个错误是因为TypeScript默认的DOM类型定义未包含Background Sync API的相关类型,导致编译器无法识别registration.sync属性。以下是两种可行的解决方式:

方法一:添加自定义类型声明(推荐)

在项目中新增类型声明文件,让TypeScript识别Background Sync的类型:

  1. 在项目根目录或src目录下创建typings.d.ts文件
  2. 写入以下类型定义代码:
interface ServiceWorkerRegistration {
  sync: SyncManager;
}

interface SyncManager {
  register(tag: string): Promise<void>;
  getTags(): Promise<string[]>;
}
  1. 确保tsconfig.json的include数组包含该文件,示例配置:
"include": [
  "src/**/*",
  "typings.d.ts"
]

方法二:使用类型断言快速修复

如果只是临时调试或不想新增类型文件,可以通过类型断言绕过类型检查:

方式1:联合类型断言(保留部分类型提示)

navigator.serviceWorker.ready.then((registration: ServiceWorkerRegistration & { sync?: SyncManager }) => {
    if (registration.sync) {
        // Background Sync is supported.
    } else {
        // Background Sync isn't supported.
    }
});

方式2:any类型断言(最简但无类型提示)

navigator.serviceWorker.ready.then(registration => {
    if ((registration as any).sync) {
        // Background Sync is supported.
    } else {
        // Background Sync isn't supported.
    }
});

注意:方法一能提供完整的类型检查和代码提示,适合长期维护的项目;方法二更适合快速验证功能的场景。

内容的提问来源于stack exchange,提问作者Kestal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 18:25:35