typescriptservice-worker

What is the correct tsconfig.json for a service worker?


Short version: TypeScript's lib: ['DOM'] does not include Service Worker types, but @types/service_worker_api says it does.

I have a working TypeScript service worker. It has no problems other than I have to use // @ts-nocheck at the top of the file, because TypeScript can't handle the service worker types.

Similar to TypeScript type definitions for ServiceWorker, I originally followed the instructions to install the types for service_worker_api:

$ npm install --save @types/service_worker_api

npm WARN deprecated @types/service_worker_api@0.0.9: ServiceWorker types are now provided by '--lib dom'

So modifying my tsconfig accordingly:

{
  "compilerOptions": {
    "rootDir": "src",
    "composite": true,
    "module": "es2020",
    "moduleResolution": "Node",
    // Resulting files will be in dist/service-worker.js
    "outDir": "dist",
    // From "@types/service_worker_api@0.0.9: ServiceWorker types are now provided by '--lib dom'"
    "lib": ["DOM"]
  },
  "include": ["src/service-worker.ts"]
}

This fails with:

$ npx tsc --project tsconfig.serviceworker.json
src/service-worker.ts(27,34): error TS2339: Property 'clients' does not exist on type 'Window & typeof globalThis'.
src/service-worker.ts(51,8): error TS2339: Property 'skipWaiting' does not exist on type 'Window & typeof globalThis'.

I also tried WebWorker - though I know WebWorker isn't quite the same as a service worker - and that fails with

src/service-worker.ts(66,56): error TS2339: Property 'data' does not exist on type 'Event'.
src/service-worker.ts(67,23): error TS2339: Property 'data' does not exist on type 'Event'.

What is the correct tsconfig.json for a service worker?


Solution

  • There’s a new @types/serviceworker from Microsoft (see, the release notes for more details) that should definitely solve the issue.

    Mine was a bit different, since I got here looking how-to solve an issue with waitUntil(), then I solved it by just setting ExtendableEvent as the event type on the service worker listeners.