Here is how I handle communication over Electron channels:
preload.ts
contextBridge.exposeInMainWorld("myIpcRenderer", {
invoke: (channel: Channel, ...args: any[]) =>
callIpcRenderer("invoke", channel, ...args),
send: (channel: Channel, ...args: any[]) =>
callIpcRenderer("send", channel, ...args),
on: (channel: Channel, ...args: any[]) =>
callIpcRenderer("on", channel, ...args),
});
types.d.ts
interface MyIpcRenderer {
invoke(channel: Channel.ReadFiles, ...args: any[]): Promise<ReadFileResult[]>;
}
The MyIpcRenderer type enforce correct use in renderer.ts:
const files = await window.myIpcRenderer.invoke(Channel.ReadFiles, [
svgPath,
]);
But it does not enforce correct use in main.ts. ipcMain.handle refers to an electron method that can accept channels with any name and retturn any kind of promise.
ipcMain.handle(
"anychannelnamegoes",
async (_event, paths: string[]): Promise<any> => {
...
}
);
How can I rewrite my code to enforce main usage in main.ts as well?