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)
Usage
1. Install from npm
npm i electron-typed-ipc --save
2. Define your events/commands
type Events = {
configUpdated: (newConfig?: Config, oldConfig?: Config) => void;
};
type Commands = {
fetchConfig: () => Config;
updateConfig: (newConfig: Partial<Config>) => void;
};
3. Add types to ipcMain
and ipcRenderer
const typedIpcMain = ipcMain as TypedIpcMain<Events, Commands>;
const typesIpcRenderer = ipcRenderer as TypedIpcRenderer<Events, Commands>;
4. Emit events and invoke commands
const config = await typedIpcRenderer.invoke('fetchConfig');
typedIpcMain.handle('fetchConfig', () => {
return { a: 1, b: 'text' };
});
typedIpcRenderer.on('configUpdated', (_, newConfig, oldConfig) => {
console.log(newConfig, oldConfig);
});
webContents
.getAllWebContents()
.forEach((renderer: TypedWebContents<Events>) => {
renderer.send('configUpdated', newConfig, oldConfig);
});