how to get serviceworker registration object which is typescript friendly?

Viewed 2687
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"],

3 Answers

Add this to the top of your file:

/// <reference lib="webworker" />
export default null
declare let self: ServiceWorkerGlobalScope

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 {}
}
Related