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