Skip to content

Commit

Permalink
docs: service worker types (#8965)
Browse files Browse the repository at this point in the history
The additional reference is needed for $service-worker to be properly typed
  • Loading branch information
dummdidumm authored Feb 9, 2023
1 parent 3aedafa commit 275bd61
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion documentation/docs/30-advanced/40-service-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ The following example caches the built app and any files in `static` eagerly, an

```js
// @errors: 2339
/// <reference types="@sveltejs/kit" />
import { build, files, version } from '$service-worker';

// Create a unique cache name for this deployment
Expand Down Expand Up @@ -108,21 +109,23 @@ navigator.serviceWorker.register('/service-worker.js', {
Setting up proper types for service workers requires some manual setup. Inside your `service-worker.js`, add the following to the top of your file:

```original-js
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
const sw = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (self));
```
```generated-ts
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
const sw = self as unknown as ServiceWorkerGlobalScope;
```

This disables access to DOM typings like `HTMLElement` which are not available inside a service worker and instantiates the correct globals. The reassignment of `self` to `sw` allows you to type cast it in the process (there are a couple of ways to do this, but the easiest that requires no additional files). Use `sw` instead of `self` in the rest of the file.
This disables access to DOM typings like `HTMLElement` which are not available inside a service worker and instantiates the correct globals. The reassignment of `self` to `sw` allows you to type cast it in the process (there are a couple of ways to do this, but the easiest that requires no additional files). Use `sw` instead of `self` in the rest of the file. The reference to the SvelteKit types ensures that the `$service-worker` import has proper type definitions.

## Other solutions

Expand Down

0 comments on commit 275bd61

Please sign in to comment.