DEV Community

Andrei Canta
Andrei Canta

Posted on

3

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more