0

I am using electron-react-boilerplate.

I am preloading events I want to use, like so:

const { contextBridge, ipcRenderer, app } = require('electron');

contextBridge.exposeInMainWorld('electron', {
  ipcRenderer: {
    on(channel, func) {
      const validChannels = [
        'bt:connected',
       ];
      if (validChannels.includes(channel)) {
        // Deliberately strip event as it includes `sender`
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      }
    },
  }
}

Then, in my main process I use the following method to communicate with my renderer process:

this.window.webContents.send('bt:connected', 'I am an address string');

Finally, in my renderer process, I catch the address using an event handler as declared in my preloader script:

window.electron.ipcRenderer.on('bt:connected', (_e: any, arg: string) => {
  doStuff(arg);
}

This works fine in javascript. Can someone please tell me how can I prevent the following error in typescript:

Argument of type '(address: string) => void' is not assignable to parameter of type '(...args: unknown[]) => void'.
  Types of parameters 'address' and 'args' are incompatible.
    Type 'unknown' is not assignable to type 'string'.ts(2345)

On my src/renderer/preload.d.ts file I declare the on(...) method like so:

on(
  channel: string,
  func: (...args: unknown[]) => void
): (() => void) | undefined;
chipimix
  • 219
  • 3
  • 12
  • 1
    Looking at the repo, I think you need to manually specify the correct types in `src/renderer/preload.d.ts`. – Oblosys Sep 15 '22 at 23:49

1 Answers1

0

I had to mannually specify the events in src/renderer/preload.ts:

export type Channels = [  'bt:connected' ]
...
on(channel: Channels, func: (...args: unknown[]) => void) {
      const subscription = (_event: IpcRendererEvent, ...args: unknown[]) =>
        func(...args);
      ipcRenderer.on(channel.toString(), subscription);

      return () => ipcRenderer.removeListener(channel.toString(), subscription);
    },
...

This solved the issue :)

chipimix
  • 219
  • 3
  • 12