TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Service Worker typings

Open jgw96 opened this issue 10 years ago • 44 comments

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.

jgw96 avatar Oct 21 '16 13:10 jgw96

@iiic https://github.com/microsoft/TypeScript/issues/14877#issuecomment-326751509

grundmanise avatar Jun 18 '20 17:06 grundmanise

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);
});

simon04 avatar Dec 23 '20 23:12 simon04

@simon04 Just it, and you don't even have to alias self. You can see it here:

TS Play

michaeljota avatar Jan 01 '21 18:01 michaeljota

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).

googol avatar Feb 24 '21 20:02 googol

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;

jhony1104 avatar Mar 22 '21 11:03 jhony1104

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'.

HolgerJeromin avatar Mar 24 '21 07:03 HolgerJeromin

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:

Glandos avatar Jul 01 '21 15:07 Glandos

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 avatar Mar 05 '22 12:03 jimmywarting

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.

Mlocik97 avatar May 03 '22 17:05 Mlocik97

The simplest solution that worked for me, is just this on the Service Worker code:

/// <reference lib="WebWorker" />

const sw: ServiceWorkerGlobalScope = self as any

alexbruno avatar Jan 03 '23 20:01 alexbruno

To avoid aliasing self, this seems to work in the latest version of TypeScript:

/// <reference lib="WebWorker" />

declare let self: ServiceWorkerGlobalScope;

F2 avatar Feb 26 '23 09:02 F2

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 😆

ShafSpecs avatar Mar 28 '23 13:03 ShafSpecs

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 avatar Mar 29 '23 13:03 icazemier

@icazemier ty :) adding to tsconfig.json:

"lib": ["WebWorker", ...], did it for me

noel-schenk avatar Mar 26 '24 09:03 noel-schenk

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.

strogonoff avatar Sep 30 '24 16:09 strogonoff

If you are using @vitejs, this works for me

  1. 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'
            }
        },
    },
},
  1. Add to the tsconfig.app.json file
"compilerOptions": {
    "lib": [
      "WebWorker"
    ],
  1. Create the src/sw.ts file and add this code
declare const self: ServiceWorkerGlobalScope;

self.addEventListener('install', (e: ExtendableEvent) => {
  ...
});

hatem-amer avatar Oct 30 '24 22:10 hatem-amer

I got it working with this at the top of my worker code

/// <reference lib="WebWorker" />
export type {}
declare let self: DedicatedWorkerGlobalScope

Gugustinette avatar Dec 22 '24 13:12 Gugustinette

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

arianvp avatar Apr 09 '25 09:04 arianvp

@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 avatar Aug 08 '25 21:08 eighty4

@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).

strogonoff avatar Aug 11 '25 03:08 strogonoff