rawnato's avatar

How can I use Laravel Echo + TypeScript?

Since I'm just starting with TypeScript, I'm not quite sure how to configure Laravel Echo to work with it. I’ve tried a few approaches like I usually do in JavaScript, but I haven’t had much success. Has anyone dealt with this before or knows how to solve it?

My code that does not work its here:

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

window.Pusher = Pusher;
window.Echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
    wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

0 likes
2 replies
rawnato's avatar

I go to this,

File: global.d.ts

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

(window as any).Pusher = Pusher;
(window as any).Echo = new Echo({
    broadcaster: 'pusher',
    key: import.meta.env.VITE_REVERB_APP_KEY as string,
    wsHost: import.meta.env.VITE_REVERB_HOST as string,
    wsPort: Number(import.meta.env.VITE_REVERB_PORT) || 80,
    wssPort: Number(import.meta.env.VITE_REVERB_PORT) || 443,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

declare global {
    interface Window {
        Pusher: any;
        Echo: Echo;
    }
}

But when I try to access window.Echo I get undefined

Schizo's avatar

It's working for me:

@/lib/echo.d.ts

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

declare global {
    interface Window {
        Echo: Echo<'reverb'>
        Pusher: typeof Pusher
    }
}

@/plugins/echo.ts

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

window.Pusher = Pusher;
window.Echo = new Echo<'reverb'>({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
    wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});
1 like

Please or to participate in this conversation.