【问题标题】:How to strong type electron.remote.require() result如何强类型 electron.remote.require() 结果
【发布时间】:2020-12-27 14:54:07
【问题描述】:

在使用Typescript开发的电子应用程序的渲染器过程中,我有例如:

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

其中Fs 的类型为any

我希望Fs 的类型为“module:fs”,但我不知道如何在 Typescript 中实现这一点:

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

有什么想法吗?

【问题讨论】:

    标签: typescript electron typescript-typings


    【解决方案1】:

    我不确定module:fs 是什么,但只要您非常确定这两个匹配项的结构,您就可以使用as 进行类型断言。

    如果你不确定,那么看看你是否可以有类似下面的东西: (请注意,这可能需要一些调整,我还没有测试过)

    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()
    

    【讨论】:

      【解决方案2】:

      您可以使用Module Augmentation 来做到这一点。

      创建一个文件,比如augmentations.d.ts 并指定其内容如下

      // 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;
        }
      }
      

      这增加了电子的Remote 接口的声明,添加了require 的重载,它将字符串文字类型"fs"@types/node 声明的NodeJS 的"fs" 模块的默认导出类型相关联,并且作为 election 的依赖项安装。

      【讨论】:

      • 完美!它就像一个魅力:remote.require('fs') 不再有这个环境声明
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 2020-10-29
      • 2023-02-10
      • 2012-10-10
      • 2021-12-15
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多