Home > Net >  How to declare webContents to TypeScript in Electron 15
How to declare webContents to TypeScript in Electron 15

Time:10-12

Description

Upgrading to Electron 14 → 15 introduces the following TypeScript build error for my main process.

error TS2749: 'webContents' refers to a value, but is being used as a type here. Did you mean 'typeof webContents'?

The delcarations in the code are

import { webContents, dialog } from 'electron';

// ...

logContents: webContents | undefined

The build gave me no problem with Electron 14 and before.

Reproduction

The problem is simple to reproduce.

  1. Clone repo.

    git clone https://github.com/pglezen/electron-typescript-svelte-starter e15
    
  2. Install dependencies.

    cd e15
    npm install
    npm ls electron
    

    This should verify Electron 14 installation.

  3. Run main process build.

    npm run build:main
    

    No errors should be encountered.

  4. Upgrade to Electron 15.

    npm install electron@15.1.0
    
  5. Rerun build.

    npm run build:main
    

The full error text is listed below.

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.

Attempted Fixes

1. Import webContents as a type.

I changed the webContents declaration to

import type { webContents } from 'electron';

Result: No change in the message.

2. Use the TypeScript typeof operator

This was suggested in the error message.

Result: Removed the above error message; but introduced the following error where I tried to invoke a function call on webContents:

TS2339: Property 'send' does not exist on type 'typeof WebContents'

CodePudding user response:

I'm guessing this API underwent some changes in the latest version. But at least as of version 15, you aren't using this API correctly.

According to the docs the value you get from the webContents module, has these methods.

And the instances of WebContents that come from BrowserWindows have these methods

These are completely different values and types.

Playground here that illustrates the difference.


You probably want the webContents that comes from BrowserWindow. In which those appear to be instances of the WebContents (note the capital W) class which you can import and use as you expect.

import { WebContents, BrowserWindow } from 'electron';

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