typescript - 如何在 Electron 15 中将 webContents 声明为 TypeScript
问题描述
描述
升级到 Electron 14 → 15 为我的主进程引入了以下 TypeScript 构建错误。
错误 TS2749:“webContents”指的是一个值,但在这里被用作一种类型。您的意思是“typeof webContents”吗?
代码中的声明是
import { webContents, dialog } from 'electron';
// ...
logContents: webContents | undefined
该版本对 Electron 14 及之前版本没有任何问题。
再生产
问题很容易重现。
克隆回购。
git clone https://github.com/pglezen/electron-typescript-svelte-starter e15
安装依赖项。
cd e15 npm install npm ls electron
这应该验证 Electron 14 的安装。
运行主进程构建。
npm run build:main
应该不会遇到任何错误。
升级到电子 15。
npm install electron@15.1.0
重新运行构建。
npm run build:main
下面列出了完整的错误文本。
src/main/Logger.ts:13:16 - error TS2749: 'webContents' refers to a value, but is being used as a type here. Did you mean 'typeof webContents'?
13 logContents: webContents | undefined;
~~~~~~~~~~~
src/main/Logger.ts:14:17 - error TS2749: 'webContents' refers to a value, but is being used as a type here. Did you mean 'typeof webContents'?
14 mainContents: webContents | undefined;
~~~~~~~~~~~
Found 2 errors.
尝试修复
webContents
1.作为类型导入。
我将webContents
声明更改为
import type { webContents } from 'electron';
结果:消息没有变化。
2. 使用 TypeScripttypeof
运算符
这是在错误消息中建议的。
结果:删除了上述错误信息;但在我尝试调用函数调用时引入了以下错误webContents
:
TS2339:“typeof WebContents”类型上不存在属性“send”
解决方案
我猜这个 API 在最新版本中发生了一些变化。但至少从版本 15 开始,您没有正确使用此 API。
根据文档,您从webContents
模块中获得的值具有这些方法。
WebContents
that from BrowserWindow
s的实例有这些方法
这些是完全不同的值和类型。
您可能想要webContents
来自BrowserWindow
. 其中那些似乎是WebContents
(注意大写W
)类的实例,您可以按预期导入和使用。
import { WebContents, BrowserWindow } from 'electron';
const windowWebContents: WebContents = new BrowserWindow().webContents
windowWebContents.send('testing') // WORKS
推荐阅读
- ios - 启动应用程序时如何克服此错误?
- javascript - TypeError:无法读取未定义 React JS 的属性“handleClick”
- html - 即使我声明它,我的网站格式也没有间隔
- python - 将数据帧作为时间序列处理时,将新数据帧与旧数据帧进行比较?
- swift - SKAction 对儿童的奇怪行为
- python-3.x - 将值分配给 ndarray 中的中断切片
- javascript - 如何将 Javascript 文件中的值返回到 Node.js,以便写入文件?
- linux - 我想 grep [Nodes]:ALL from
- python - 如何访问在 `with` 语句中创建的变量
- typescript - 打字稿中所有对象文字类型的子类型?