Skip to content

Commit 9dd666c

Browse files
aawnuChew Tee MingRich-Harris
authored
docs: update type-casting of "self" without re-declaration in service-worker (#13624)
* Update typing of "self" without redeclaration in serviceworker * use self = globalThis.self trick --------- Co-authored-by: Chew Tee Ming <[email protected]> Co-authored-by: Rich Harris <[email protected]>
1 parent 1d99607 commit 9dd666c

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

documentation/docs/30-advanced/40-service-workers.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,8 @@ The following example caches the built app and any files in `static` eagerly, an
3838

3939
import { build, files, version } from '$service-worker';
4040

41-
// The reassignment of `self` to `sw` allows you to type cast it in the process
42-
// (this is the easiest way to do it without needing additional files)
43-
const sw = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (self));
41+
// This gives `self` the correct types
42+
const self = /** @type {ServiceWorkerGlobalScope} */ (/** @type {unknown} */ (globalThis.self));
4443

4544
// Create a unique cache name for this deployment
4645
const CACHE = `cache-${version}`;
@@ -50,7 +49,7 @@ const ASSETS = [
5049
...files // everything in `static`
5150
];
5251

53-
sw.addEventListener('install', (event) => {
52+
self.addEventListener('install', (event) => {
5453
// Create a new cache and add all files to it
5554
async function addFilesToCache() {
5655
const cache = await caches.open(CACHE);
@@ -60,7 +59,7 @@ sw.addEventListener('install', (event) => {
6059
event.waitUntil(addFilesToCache());
6160
});
6261

63-
sw.addEventListener('activate', (event) => {
62+
self.addEventListener('activate', (event) => {
6463
// Remove previous cached data from disk
6564
async function deleteOldCaches() {
6665
for (const key of await caches.keys()) {
@@ -71,7 +70,7 @@ sw.addEventListener('activate', (event) => {
7170
event.waitUntil(deleteOldCaches());
7271
});
7372

74-
sw.addEventListener('fetch', (event) => {
73+
self.addEventListener('fetch', (event) => {
7574
// ignore POST requests etc
7675
if (event.request.method !== 'GET') return;
7776

0 commit comments

Comments
 (0)