首页 > 解决方案 > 如何在 Electron 15 中将 webContents 声明为 TypeScript

问题描述

描述

升级到 Electron 14 → 15 为我的主进程引入了以下 TypeScript 构建错误。

错误 TS2749:“webContents”指的是一个值,但在这里被用作一种类型。您的意思是“typeof webContents”吗?

代码中的声明是

import { webContents, dialog } from 'electron';

// ...

logContents: webContents | undefined

该版本对 Electron 14 及之前版本没有任何问题。

再生产

问题很容易重现。

  1. 克隆回购。

    git clone https://github.com/pglezen/electron-typescript-svelte-starter e15
    
  2. 安装依赖项。

    cd e15
    npm install
    npm ls electron
    

    这应该验证 Electron 14 的安装。

  3. 运行主进程构建。

    npm run build:main
    

    应该不会遇到任何错误。

  4. 升级到电子 15。

    npm install electron@15.1.0
    
  5. 重新运行构建。

    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.

尝试修复

webContents1.作为类型导入。

我将webContents声明更改为

import type { webContents } from 'electron';

结果:消息没有变化。

2. 使用 TypeScripttypeof运算符

这是在错误消息中建议的。

结果:删除了上述错误信息;但在我尝试调用函数调用时引入了以下错误webContents

TS2339:“typeof WebContents”类型上不存在属性“send”

标签: typescriptelectron

解决方案


我猜这个 API 在最新版本中发生了一些变化。但至少从版本 15 开始,您没有正确使用此 API。

根据文档,您从webContents模块中获得的值具有这些方法

WebContentsthat from BrowserWindows的实例有这些方法

这些是完全不同的值和类型。

这里的操场说明了差异。


您可能想要webContents来自BrowserWindow. 其中那些似乎是WebContents(注意大写W)类的实例,您可以按预期导入和使用。

import { WebContents, BrowserWindow } from 'electron';

const windowWebContents: WebContents = new BrowserWindow().webContents
windowWebContents.send('testing') // WORKS

推荐阅读