DEV Community

Andrei Canta
Andrei Canta

Posted on

Electron Typed IPC

  • no runtime cost (just typescript enhancements)
  • keeps the same API as Electron
  • separates events from commands to avoid confusions
    • events are things that happened (IPC)
    • commands are async functions you can invoke (RPC)

1. Install electron-typed-ipc from NPM

npm i electron-typed-ipc --save
Enter fullscreen mode Exit fullscreen mode

2. Define your events/commands

type Events = {
  configUpdated: (newConfig?: Config, oldConfig?: Config) => void;
};

type Commands = {
  fetchConfig: () => Config;
  updateConfig: (newConfig: Partial<Config>) => void;
};
Enter fullscreen mode Exit fullscreen mode

3. Add types to ipcMain and ipcRenderer

const typedIpcMain = ipcMain as TypedIpcMain<Events, Commands>;
const typesIpcRenderer = ipcRenderer as TypedIpcRenderer<Events, Commands>;
Enter fullscreen mode Exit fullscreen mode

4. Emit events and invoke commands

// renderer.js
const config = await typedIpcRenderer.invoke('fetchConfig');

// main.js
typedIpcMain.handle('fetchConfig', () => {
  return { a: 1, b: 'text' };
});
Enter fullscreen mode Exit fullscreen mode
// renderer.js
typedIpcRenderer.on('configUpdated', (_, newConfig, oldConfig) => {
  console.log(newConfig, oldConfig);
});

// main.ts
webContents
  .getAllWebContents()
  .forEach((renderer: TypedWebContents<Events>) => {
    renderer.send('configUpdated', newConfig, oldConfig);
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)