How to us laravel-echo and pusher-js with Typescript

114 Views Asked by At

I am trying to install and use laravel-echo and pusher-js. I have the following:

bootstrap.ts

import Pusher from 'pusher-js';
import Echo from 'laravel-echo';

window.Pusher = Pusher;

window.Echo = new Echo({
  broadcaster: 'pusher',
  key: import.meta.env.VITE_PUSHER_APP_KEY,
  wsHost: import.meta.env.VITE_PUSHER_HOST ?? `ws-${import.meta.env.VITE_PUSHER_CLUSTER}.pusher.com`,
  wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
  wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
  forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
  enabledTransports: ['ws', 'wss'],
});

However, I get two errors

Property 'Pusher' does not exist on type 'Window & typeof globalThis'.
Property 'Echo' does not exist on type 'Window & typeof globalThis'.

What is going wrong here?

1

There are 1 best solutions below

0
Jerwin Mathew Aton On

I have the same problem while learning laravel with react typescript, this one worked for me

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;

//add these
declare global {
    interface Window {
        Pusher: any; 
        Echo: Echo; 
    }
}

and use it in app.tsx via window.Echo

window.Echo.channel('messenger').listen('MessageSent', (e: any) => {
    console.log(e);
});