【问题标题】:How do you assign the type of an entire module to a destructured variable?如何将整个模块的类型分配给解构变量?
【发布时间】:2019-05-04 22:21:36
【问题描述】:

我正在尝试向 CommonJS 模块添加依赖注入,以便在测试时轻松模拟 HTTP 调用。

有效的旧代码(Flow 知道 http 的类型):

const myModule = require('./my-module.js');

 

// my-module.js
const http = require('http');
module.exports = {
  doSomething: () => http.get(...);
};

新代码,不起作用:

const myModule = require('./my-module.js')({http: require('http')});

 

// my-module.js
module.exports = ({ http }) => ({
  doSomething: () => http.get(...);
});

我收到错误消息“缺少用于解构的类型注释”。而且我不知道要使用什么类型的注释。

我尝试用各种东西注释 http 属性并查看会发生什么,但无济于事,例如:

type ModuleOptions = $ReadOnly<{
  http: typeof require('http'),
}>;

module.exports = ({ http }: ModuleOptions) => ({

有什么想法吗?

【问题讨论】:

    标签: javascript node.js flowtype


    【解决方案1】:

    它一定会发生。在花了几个小时谷歌搜索和尝试之后,在 SO 上发布的半小时内我就明白了:

    import typeof HttpModule from 'http';
    type ModuleOptions = $ReadOnly<{
      http: HttpModule
    }>;
    
    module.exports = ({ http }: ModuleOptions) => {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多