You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TypeScript中使用laravel-echo与pusher-js遇类型错误的咨询

解决Laravel Echo + Pusher-JS的TypeScript全局类型错误

这两个错误是因为TypeScript默认的Window全局类型中没有定义Pusher和Echo属性,导致类型检查不通过。以下是具体解决方法:

方法一:扩展全局Window类型

在项目中创建一个TypeScript声明文件(比如global.d.ts,位置可放在src/types/或resources/js/types/,根据你的项目结构调整),内容如下:

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

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

然后确保你的tsconfig.json的include数组包含这个声明文件的路径,比如:

{
  "include": [
    "resources/js/**/*",
    "**/*.d.ts"
  ]
}

方法二:安装缺失的类型依赖(针对Pusher)

如果pusher-js的类型未被正确识别,安装对应的类型包:

npm install @types/pusher-js --save-dev
# 或使用yarn
yarn add @types/pusher-js --dev

方法三:避免挂载到Window(可选)

如果不需要在全局范围内访问Pusher和Echo,可以直接在需要使用的模块中导入,无需挂载到window上,这样就能绕过类型错误:

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

const 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'],
});

// 在需要的地方使用echo即可

内容的提问来源于stack exchange,提问作者matt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:37:17