Module augmentation - Typesafe Electron IPC

Hey 👋 I want to extend the Electron type definitions to make the channels for IPC communication more typesafe. For this, I'll need to override the types of the class BrowserWindow. Only the types, the underlying JavaScript will be the same. The problem is, I can't figure out how to override the electron module type defintions without running into Duplicate identifier or Cannot redeclare block-scoped variable.
1 Reply
domi?
domi?OP•3y ago
A simplified version of the type definitions provided by electron:
// types.d.ts
declare namespace Electron {
class BrowserWindow {
readonly webContents: WebContents;
}

class WebContents {
send(channel: string, ...args: any[]): void;
}

interface IpcRenderer {
on(channel: string, listener: (event: any, ...args: any[]) => void): this;
}

namespace CrossProcessExports {
class BrowserWindow extends Electron.BrowserWindow {}

const ipcRenderer: IpcRenderer;

type IpcRenderer = Electron.IpcRenderer;
}
}

declare module 'electron' {
export = Electron.CrossProcessExports;
}
// types.d.ts
declare namespace Electron {
class BrowserWindow {
readonly webContents: WebContents;
}

class WebContents {
send(channel: string, ...args: any[]): void;
}

interface IpcRenderer {
on(channel: string, listener: (event: any, ...args: any[]) => void): this;
}

namespace CrossProcessExports {
class BrowserWindow extends Electron.BrowserWindow {}

const ipcRenderer: IpcRenderer;

type IpcRenderer = Electron.IpcRenderer;
}
}

declare module 'electron' {
export = Electron.CrossProcessExports;
}
My override file:
// overrides.d.ts

type ActiveChannels = 'channel1' | 'channel2' | 'channel3';

declare namespace Electron {
class WebContents { // Duplicate identifier 'WebContents'.ts(2300)
send(channel: ActiveChannels, ...args: any[]): void;
}

interface IpcRenderer {
on(channel: ActiveChannels, listener: (event: any, ...args: any[]) => void): this;
}
}
// overrides.d.ts

type ActiveChannels = 'channel1' | 'channel2' | 'channel3';

declare namespace Electron {
class WebContents { // Duplicate identifier 'WebContents'.ts(2300)
send(channel: ActiveChannels, ...args: any[]): void;
}

interface IpcRenderer {
on(channel: ActiveChannels, listener: (event: any, ...args: any[]) => void): this;
}
}
Want results from more Discord servers?
Add your server