7
self.addEventListener('push', function(event:any) {
  console.log('Push event!! ', event)
  
  if (event.data) {
    console.log('This push event has data: ', event.data.text());
  } else {
    console.log('This push event has no data.');
  }

  
  const promiseChain = showLocalNotification('Yolo', event.toString(), self.registration);

  event.waitUntil(promiseChain);
  
})

Here the line const promiseChain = showLocalNotification('Yolo', event.toString(), self.registration); complains about self.registration:

Property 'registration' does not exist on type 'Window & typeof globalThis'.ts(2339)

How do I resolve this? Any pointer here would be greatly appreciated.

In my tsconfig i'm already using dom lib option.

"lib": [ "es2015" , "dom"],

sahilsk
  • 133
  • 1
  • 8

3 Answers3

11

Please see https://github.com/microsoft/TypeScript/issues/14877#issuecomment-493729050

The following two steps should help:

  • Include a references to the webworker library in either your tsconfig's compilerOptions or via a triple-slash directive in your service worker TypeScript file.

  • Inside your service worker TypeScript file, declare var self: ServiceWorkerGlobalScope; to tell TypeScript that self is an instance of the ServiceWorkerGlobalScope.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
9

Add this to the top of your file:

/// <reference lib="webworker" />
export default null
declare let self: ServiceWorkerGlobalScope
Maurici Abad
  • 1,012
  • 9
  • 20
  • 1
    What's `export default null`? – azizj Mar 04 '22 at 19:32
  • @azizj I don't understand it either, I just know it works. If someone else knows, enlighten us. – Maurici Abad Mar 07 '22 at 10:22
  • 3
    The reason for `export default null` is to prevent the error `TS1208: 'service-worker.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.`. See also [here](https://stackoverflow.com/a/56577324/3927228). – eega May 03 '22 at 14:50
  • worked even without `export default null` for me. – Rohit Kaushal Sep 28 '22 at 11:48
-1

You can also add @types/global.d.ts file and add:

export declare global {
  interface Window extends ServiceWorkerGlobalScope {}
  
  // need for addEventListener
  interface WindowEventMap extends ServiceWorkerGlobalScopeEventMap {}
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Val1991
  • 152
  • 1
  • 4