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?
I found a lot of up to date information in Joshua T's blog post Strongly Typed Web and Service Workers with TypeScript.
There are some big open issues with Web Worker types that are blocking easier solutions for strong-typing service worker files.
Following 'Solution B: TSConfig Libs' - yes, use 'WebWorker':
{
"compilerOptions": {
"rootDir": "src",
"composite": true,
"module": "es2020",
"moduleResolution": "Node",
// Resulting files will be in dist/service-worker.js
"outDir": "dist",
// From https://joshuatz.com/posts/2021/strongly-typed-service-workers/
"lib": ["WebWorker", "ES2015"]
},
"include": ["src/service-worker.ts"]
}
Note, as VS Code only supports a single tsconfig.json for a project, you may still need to add @ts-ignore
to some lines.