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

Electron-React-Typescript应用中解决Window类型不存在api属性的报错问题

解决Electron-React-Typescript中Property 'api' does not exist on type 'Window & typeof globalThis'错误

你的问题根源很明确:你把Window接口的扩展嵌套在了NodeJS命名空间里,但Window是浏览器全局环境的核心接口,并不属于NodeJS的命名空间,所以TypeScript完全识别不到你对它的类型扩展。

修正步骤:

  1. 调整index.d.ts的类型声明结构
    把Window接口直接放在global作用域下,不要嵌套在NodeJS里,同时记得加上export {}让文件被当作模块处理(这是TypeScript识别全局类型扩展的必要条件)。修正后的代码如下:
declare global {
  interface Window {
    electron: {
      openNewWindow(): void;
    };
    api: {
      send: (channel: string, data: unknown) => void;
      receive: (channel: string, func: (...args: unknown[]) => void) => void;
      electronIpcSendTo: (window_id: string, channel: string, ...arg: unknown[]) => void;
      electronIpcSend: (channel: string, ...arg: unknown[]) => void;
      electronIpcSendSync: <T = unknown>(channel: string, ...arg: unknown[]) => T;
      electronIpcOn: (channel: string, listener: (event: Electron.IpcRendererEvent, ...arg: unknown[]) => void) => void;
      electronIpcOnce: (channel: string, listener: (event: Electron.IpcRendererEvent, ...arg: unknown[]) => void) => void;
      electronIpcRemoveListener: (channel: string, listener: (event: Electron.IpcRendererEvent, ...arg: unknown[]) => void) => void;
      electronIpcRemoveAllListeners: (channel: string) => void;
    };
  }
}

// 必须添加这一行,让TypeScript将该文件视为模块
export {};
  1. 确保类型文件被TypeScript编译识别
    检查你的tsconfig.json,确认include数组包含了这个.d.ts文件,比如:

    {
      "include": [
        "src/**/*",
        "src/index.d.ts" // 或者更通用的"./src/**/*.d.ts"
      ]
    }
    
  2. 重启TypeScript语言服务
    如果你用VSCode开发,按Ctrl+Shift+P打开命令面板,选择TypeScript: Restart TS Server,让新的类型声明生效(有时候编辑器不会自动识别文件修改)。

  3. 确认preload脚本的挂载逻辑正确
    别忘了你的Electron preload脚本里确实把api对象挂载到了window上,比如:

    // preload.ts
    import { ipcRenderer } from 'electron';
    
    window.api = {
      send: (channel, data) => {
        ipcRenderer.invoke(channel, data).catch(e => console.error(e));
      },
      receive: (channel, func) => {
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      },
      // 实现其他api方法...
    };
    
    window.electron = {
      openNewWindow: () => {
        // 你的实现逻辑
      }
    };
    

额外优化建议:

我给你修正后的类型声明里把参数从any改成了unknown,并且给electronIpcSendSync加上了泛型,这样可以让你的代码更符合TypeScript的类型安全原则,避免不必要的类型隐患。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 07:18:16