Beau
Beau

Reputation: 11358

Missing typings when using window.require with Electron and TypeScript with create-react-app

I have an Electron app that uses create-react-app with the TypeScript configuration (which uses Babel to compile the TypeScript code to JavaScript).

I've followed the advice to use window.require in this case when importing modules like electron-store which access the filesystem, to avoid collision with Babel's require (which would error out with e.g. fs.whatever not found).

My issue is that these modules come in typed as any, even when typing information is available. How do I clue TypeScript into the typing information for modules imported with window.require?

To make it specific, here's an example:

const Store = window.require('electron-store');

type StoreType = {
  'root-path': string;
};

// fails with "Untyped function calls may not accept type arguments."
export const store = new Store<StoreType>();

Upvotes: 1

Views: 2267

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31803

This cannot be done generically, that is to say for arbitrary module specifiers, but I suspect only a few modules will be loaded this way. Given that, your best bet is to write something like

 // augmentations.d.ts or whatever you want to call it.

 import ElectronStore from 'electron-store';

 declare global {
   interface Window {
     require(moduleSpecifier: 'electron-store'): typeof ElectronStore;
     require(moduleSpecifier: 'some-specifier'): SomeType; 
   }
 }

Upvotes: 1

Related Questions