Electron preload.ts 类型无法自动推导的解决方案

Electron preload.ts 类型无法自动推导的解决方案

在 Electron 中通过 contextBridge.exposeInMainWorld() 暴露 API:

javascript 复制代码
// preload.ts
import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('electron', {
  puppeteer: () => ipcRenderer.invoke('puppeteer'),
  db: () => ipcRenderer.invoke('db'),
});

Renderer 中调用:

javascript 复制代码
await window.electron.puppeteer();

TypeScript 会报错:

rust 复制代码
Property 'electron' does not exist on type 'Window & typeof globalThis'

原因是:

contextBridge.exposeInMainWorld() 只是在运行时向 window 注入对象,TypeScript 并不会根据 preload.ts 自动推导出:

javascript 复制代码
window.electron

的类型。

因此需要手动定义类型声明,并让 preload.ts 和 Renderer 共用同一套类型。

1. 定义 Electron API 类型

创建:

bash 复制代码
src/types/electron.ts
typescript 复制代码
export interface ElectronAPI {
  puppeteer(): Promise<void>;
  db(): Promise<unknown>;
}

以后所有暴露给 Renderer 的 Electron API,都统一维护在这里。

2. preload.ts 使用同一个类型

typescript 复制代码
import { contextBridge, ipcRenderer } from 'electron';
import type { ElectronAPI } from './types/electron';

const electronAPI: ElectronAPI = {
  puppeteer: () => ipcRenderer.invoke('puppeteer'),
  db: () => ipcRenderer.invoke('db'),
};

contextBridge.exposeInMainWorld('electron', electronAPI);

这样 preload.ts 本身也会受到 TypeScript 类型检查。

例如 ElectronAPI 中声明了:

javascript 复制代码
puppeteer(): Promise<void>;

electronAPI 中漏掉了这个方法,TypeScript 会直接提示错误。

这样可以避免接口类型和实际 preload 实现不一致。

3. 给 window.electron 增加全局类型

创建:

bash 复制代码
src/types/global.d.ts
typescript 复制代码
import type { ElectronAPI } from './electron';

declare global {
  interface Window {
    electron: ElectronAPI;
  }
}

export {};

之后 Renderer 中就可以直接使用:

javascript 复制代码
await window.electron.puppeteer();

const result = await window.electron.db();

同时也会有完整的 IDE 自动补全和 TypeScript 类型检查。

相关推荐
泯泷5 小时前
那段文字是谁删的?Yjs 14 正式版之前,一套删除归属方案的实现与边界
前端·javascript·算法
野槐8 小时前
前端项目优化(有了我,会发生...)
前端
aa小小9 小时前
【无标题】
前端
计算机魔术师10 小时前
还在单线程跟 AI 聊天?Claude Code 并行多会话让你一个人干三个人的活
前端
志尊宝10 小时前
Vue3 零基础每日笔记(038):亲手封装 useDebounceFn 与 useThrottleFn——高频事件的流量阀
前端·javascript·vue·html·vue3
JavaGuide10 小时前
对标 MinIO!全新一代分布式文件系统正式发布
前端·后端
风骏时光牛马10 小时前
AI驱动自动化业务工作流搭建实践
前端
码云之上10 小时前
Skill 里的脚本终于能跑了,星悟接 CubeSandbox 的纪实
前端·人工智能·前端框架
IT_陈寒10 小时前
Vue computed属性这个坑,我居然踩了三次才爬出来
前端·人工智能·后端
烈风逍遥11 小时前
第三篇:组件化实践,SpTable 通用表格组件设计
前端·架构