How to strong type electron.remote.require() result

Viewed 141

In the renderer process of an electron application developed with Typescript, I have for instance:

import {remote} from 'electron';
const Fs = remote.require('fs');

where Fs is of type any

I would like Fs to be of type "module:fs" but I don't know how to achieve this in Typescript:

const Fs = remote.require('fs') // as module:fs ??

Any idea?

2 Answers

You can do this with Module Augmentation.

Create a file, say augmentations.d.ts and specify its contents as follows

// Augmentations are only valid in modules.
// This ensures this file is parsed as a module.
export {} 

import fs from 'fs';

declare module 'electron' {
  interface Remote {
    require(moduleSpecifier: 'fs'): typeof fs;
  }
}

This augments the declaration of electron's Remote interface, adding an overload of require which associates the string literal type "fs" with the type of the default export of NodeJS's "fs" module as declared by @types/node and installed as a dependency of election.

I am not sure about what module:fs is, but as long as you very sure that structure of both matches then you can use type assertion using as.

If you are not sure, then see if you can have something like below: (Note that this may need some tweaking and i have not tested this)

function isFs(obj: any): pet is module:fs {
  return (obj as module:fs).xxx !== undefined;
}


const getFs = () => {
 const fs = remote.require('fs')
 if(isFs(fs)) return fs
 else throw TypeError(`remote.require('fs') can not be cast to module:fs`)
}

const Fs = getFs()
Related