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

I've since solved it with project references to scope libs to specific code. First time using project references within one webapp and for refs between packages of a monorepo.

I was sad to find that the project references feature can't be hijacked within a bundler built webapp codebase to control the self scope and APIs available for window and worker portions of the app because you would need to add noEmit: false for code that doesn't ever need to be emitted.

eighty4 avatar Sep 01 '25 22:09 eighty4

@ShafSpecs and @Gugustinette solutions break Firefox compatibility because this issue breaks any ServiceWorker scripts that are use export or import. Here is what worked for me: In the tsconfig file, add:

"compilerOptions": {
  "skipLibCheck": true
}

In the ServiceWorker script, add:

/// <reference lib="WebWorker" />
/// <reference lib="es6" />
/// <reference no-default-lib="true"/>
const _self = (self as unknown) as ServiceWorkerGlobalScope

Then, use _self in place of self in the ServiceWorker.

This is ugly and skipLibCheck may degrade type accuracy, but I haven't found any other way to support Firefox with this nasty combination of long-running issues.

FusillyCode avatar Oct 07 '25 14:10 FusillyCode

Is there any progress on this issue? Are developers still doomed to write ServiceWorker code with one eye on the documentation, without the ability to rely on autocompletion and type checking tools?

vadimmos avatar Apr 07 '26 14:04 vadimmos

This issue will be 10 years old in a few months! Service Workers are used extensively, and yet they still aren't supported properly by TypeScript (and in turn the JS language server in VSCode). The various workarounds are ridiculous and lead to ugly code that is much more difficult to maintain.

So is this just a matter of nobody bothering to do it? Like if someone forked the code, added a 'serviceworker' lib definition separate from 'webworker', and then submitted a pull request, would it actually get merged?

supernovus avatar May 14 '26 21:05 supernovus