Electron15升级后TypeScript中webContents用作类型报错如何解决
问题根因
Electron v15 修复了此前类型定义的不规范漏洞:小写的webContents是主进程提供的全局工具对象(用于执行webContents.getAllWebContents()等全局操作),并非实例类型;单个webContents实例的正确类型是首字母大写的WebContents。v14及更早版本的类型定义允许混淆使用二者,升级后严格校验就会触发报错。
正确修复方案
- 调整导入语句,同时按需导入工具对象
webContents和实例类型WebContents:
import { webContents, dialog, type WebContents } from 'electron';
如果你的TypeScript版本不支持同一句导入里同时混导值和类型,可以拆分写:
import { webContents, dialog } from 'electron'; import type { WebContents } from 'electron';
- 替换所有类型注解处的写法:
// 把小写的webContents替换成大写的WebContents logContents: WebContents | undefined mainContents: WebContents | undefined
此前尝试失败的原因
- 直接
import type { webContents }导入的依然是全局工具对象的类型,不是实例类型,自然无法解决报错。 - 加
typeof webContents拿到的是全局工具对象的类型,该对象上不存在实例方法send,因此调用实例方法时会触发新的报错。
修改完成后重新执行构建即可消除所有报错。
内容的提问来源于stack exchange,提问作者pglezen
相关产品推荐
相关产品推荐

