getting "Property 'data' does not exist on type 'Event'" on a PushEvent

91 Views Asked by At

I'm trying to write to a service worker to receive push notifications. To display the notification the way I want, I need to listen to the event when the notification arrives on the device and get the information I want to be displayed in the notification from there. For this I use a 'push' eventListener and take the data property of that event.

self.addEventListener('push', event => {
  const data = event.data.json();
  console.log('New notification', data);
  self.registration.showNotification(data.title, {
    body: data.body,
    icon: "./favicon.ico"
    });
  });

When im trying to make reference to the data property of the event (event.data) it says there is no property "data"

Here is a screenshot

Although when I console.log the event, data is right there, along with other properties that visual studio DOES recognice, such as isTrusted

PushEvent {isTrusted: true, data: PushMessageData, type: 'push', target: ServiceWorkerGlobalScope, currentTarget: ServiceWorkerGlobalScope, …}

Screenshot

this is also another error im getting

1

There are 1 best solutions below

0
Adebisi On

In your tsconfig.json add the following to you compilerOptions

"lib": ["ES2020", "DOM", "DOM.Iterable", "WebWorker"]

Then paste this at the top of you external service-worker file

import { precacheAndRoute } from 'workbox-precaching'

declare let self: ServiceWorkerGlobalScope

precacheAndRoute(self.__WB_MANIFEST)

Then in your service worker add a type of PushEvent to the event like so

self.addEventListener('push', (event : PushEvent) => {
    const data = event.data.json();
    console.log('New notification', data);
    self.registration.showNotification(data.title, {
        body: data.body,
        icon: "./favicon.ico"
    });
});

That should solve the issue along with the error "Property 'registration' does not exist on type 'Window & typeof globalThis'"

For additional reference use the vite official Link to docs