Service Worker typings
TypeScript Version: 2.0.3
Types for Service Workers should be built into the default definitions for TypeScript. There are some good examples out there of Service Worker typings from the community.
@iiic https://github.com/microsoft/TypeScript/issues/14877#issuecomment-326751509
For JavaScript, the following snippet helped to bring IntelliSense to Visual Studio Code by making use of JSDoc:
// service-worker.js
/// <reference no-default-lib="true"/>
/// <reference lib="es2015" />
/// <reference lib="webworker" />
/**
* @type {ServiceWorkerGlobalScope}
*/
const sw = self;
sw.addEventListener("install", event => {
console.log(event);
console.log(sw.caches);
console.log(sw.registration);
});
Not aliasing self works if you are writing a web worker, but to use the service worker events like install, you can't just use self out of the box. These events are only defined in the ServiceWorkerGlobalScope interface.
What I ended up using today is:
const sw: ServiceWorkerGlobalScope & typeof globalThis = self as any
alongside separate tsconfigs that specify different libs and includes (and extend a common base).
I don't know if this is a good idea, but one could, instead of aliasing self, change the typing of self with something like:
declare var self: ServiceWorkerGlobalScope & typeof globalThis;
I don't know if this is a good idea, but one could, instead of aliasing self, change the typing of self with something like:
At least my TypeScript 4.0 setup is not happy:
1>CacheManagement\ServiceWorker.ts(6,13): error TS2403: Build:Subsequent variable declarations must have the same type.
Variable 'self' must be of type 'WorkerGlobalScope & typeof globalThis', but here has type 'ServiceWorkerGlobalScope & typeof globalThis'.
With TypeScript 4.3, I now have the following:
/// <reference no-default-lib="true"/>
/// <reference lib="es2020" />
/// <reference lib="WebWorker" />
const sw = self as ServiceWorkerGlobalScope & typeof globalThis
The no-default-lib is needed to workaround the fact that self is also a Window and not castable.
Of course, now, you must use sw and not self :disappointed:
for jsdoc and vanilla js developers:
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="WebWorker" />
const sw = /** @type {ServiceWorkerGlobalScope & typeof globalThis} */ (globalThis)
jimmywarting thanks for that solutions, even tho, it gave me another error, now from ESLint:
'globalThis' is not defined.eslint[no-undef](https://eslint.org/docs/rules/no-undef)
as well as TypeScript gave error:
Conversion of type 'Window & typeof globalThis' to type 'ServiceWorkerGlobalScope & typeof globalThis' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'Window & typeof globalThis' is missing the following properties from type 'ServiceWorkerGlobalScope': clients, onactivate, onfetch, oninstall, and 5 more.ts(2352)
So I did this:
/// env serviceworker
const globalThis = /** @type {unknown} */ (self);
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="WebWorker" />
const sw = /** @type {ServiceWorkerGlobalScope & typeof globalThis} */ (globalThis)
yeah, that's crazy.
The simplest solution that worked for me, is just this on the Service Worker code:
/// <reference lib="WebWorker" />
const sw: ServiceWorkerGlobalScope = self as any
To avoid aliasing self, this seems to work in the latest version of TypeScript:
/// <reference lib="WebWorker" />
declare let self: ServiceWorkerGlobalScope;
To avoid aliasing
self, this seems to work in the latest version of TypeScript:/// <reference lib="WebWorker" /> declare let self: ServiceWorkerGlobalScope;
It gives an error:
Cannot redeclare block-scoped variable 'self'
Using this instead worked:
/// <reference lib="WebWorker" />
export type {};
declare let self: ServiceWorkerGlobalScope;
Yep, it's getting weirder 😆
This works for me (for now... 🤷🏻 ):
/// <reference lib="esnext" />
/// <reference lib="webworker" />
/// <reference no-default-lib="true"/>
// service-worker.ts
(() => {
const initializeSW = (sw: ServiceWorkerGlobalScope) => {
sw.addEventListener('install', (event: ExtendableEvent) => {
// eslint-disable-next-line no-console
console.log(event);
});
// see: https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim
sw.addEventListener('activate', (event: ExtendableEvent) => {
// eslint-disable-next-line no-console
console.log(event);
event.waitUntil(sw.clients.claim());
});
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
initializeSW(self as any);
})();
tsconfig:
{
"compilerOptions": {
"allowJs": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"strictNullChecks": true,
"useUnknownInCatchVariables": false,
"lib": ["WebWorker", "ESNext"],
"noEmit": true,
"strict": true,
"outDir": "./public/sw",
"module": "esnext",
"target": "esnext",
"incremental": false,
"sourceMap": true,
"isolatedModules": false,
"moduleResolution": "node",
"resolveJsonModule": true
},
"include": ["service-worker.ts"],
"exclude": ["node_modules"]
}
"typescript": "^5.0.2",
@icazemier ty :) adding to tsconfig.json:
"lib": ["WebWorker", ...],
did it for me
Somehow lib doesn’t work for me, but @icazemier’s
/// <reference lib="esnext" />
/// <reference lib="webworker" />
/// <reference no-default-lib="true"/>
preamble, together with declare const self: ServiceWorkerGlobalScope;, seems to do the trick but unfortunately due to https://github.com/Microsoft/TypeScript/issues/19978 it breaks other sibling modules that do run in DOM context.
It would be an imperfect a good solution otherwise, with the added benefit of disabling the DOM or other libs that would have no effect in service worker context.
I plan to try addressing this later by having multiple sub-projects with dedicated tsconfig.json files, though that would somewhat complicate build process and it’s unclear whether it’ll even work.
If you are using @vitejs, this works for me
- Add to the vite.config.ts file
build: {
rollupOptions: {
input: {
app: './index.html',
'sw': './src/sw.ts',
},
output: {
entryFileNames: assetInfo => {
return assetInfo.name === 'sw' ? '[name].js' : 'assets/[name]-[hash].js'
}
},
},
},
- Add to the tsconfig.app.json file
"compilerOptions": {
"lib": [
"WebWorker"
],
- Create the src/sw.ts file and add this code
declare const self: ServiceWorkerGlobalScope;
self.addEventListener('install', (e: ExtendableEvent) => {
...
});
I got it working with this at the top of my worker code
/// <reference lib="WebWorker" />
export type {}
declare let self: DedicatedWorkerGlobalScope
It seems typings are missing for InstallEvent
and thus there are no types for https://developer.mozilla.org/en-US/docs/Web/API/InstallEvent/addRoutes
@Gugustinette solution worked for me to get self.onconnect from SharedWorkerGlobalScope. Why does /// <reference lib="WebWorker" /> work to access SharedWorkerGlobalScope but tsconfig.json's "lib": ["WebWorker"] does not?
/// <reference lib="WebWorker" />
declare let self: SharedWorkerGlobalScope
self.onconnect = (e: MessageEvent) => {
self.onconnect with the tsconfig.json lib specified becomes an error if I remove the reference comment. So confused!
@eighty4 do you have only one tsconfig.json? Do you use it with TSC directly or with some other tooling that respects tsconfig.json (e.g., esbuild, VSC, etc.)? Make sure the tsconfig.json that you think has effect indeed has effect, and you don’t accidentally override something through tsconfig inheritance.
Note that if you share that tsconfig in a project where you also have non-worker code, and you add WebWorker to lib, worker types will apply in non-worker code, which will confuse type validation (e.g., self.onconnect will not raise an error if you use it in your main browser window).