Simply put: TypeScript's lib: ['DOM']
does not incorporate Service Worker types, despite @types/service_worker_api
indicating otherwise.
I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck
at the beginning of the file because TypeScript struggles with the service worker types.
In line with guidance from TypeScript type definitions for ServiceWorker, I initially followed the steps to install types for service_worker_api
:
$ npm install --save @types/service_worker_api
npm WARN deprecated @types/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d3e283f3b242e28123a223f26283f122c2c240d7d637d6374">[email protected]</a>: ServiceWorker types are now provided by '--lib dom'
Therefore, I adjusted my tsconfig as follows:
{
"compilerOptions": {
"rootDir": "src",
"composite": true,
"module": "es2020",
"moduleResolution": "Node",
// Output files will be in dist/service-worker.js
"outDir": "dist",
// From "@types/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c7f697e7a656f69537b637e67697e536c66455c55674719">[email protected]</a>: ServiceWorker types are now provided by '--lib dom'"
"lib": ["DOM"]
},
"include": ["src/service-worker.ts"]
}
This results in an error:
$ 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 experimented with WebWorker
- even though WebWorker differs from a service worker - and encountered this failure:
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 appropriate tsconfig.json
for a service worker?