【问题标题】:Adding a libdef for a commonjs module exporting a function为导出函数的 commonjs 模块添加 libdef
【发布时间】:2017-04-26 23:39:21
【问题描述】:

我正在尝试为微库及其main exported function 添加类型。我为它创建了一个这样的 libdef:

流式/micro.js

// @flow
import type { Server, IncomingMessage, ServerResponse } from "http"

declare module "micro" {
  declare module.exports: {
    (): (fn: (req: IncomingMessage, res: ServerResponse) => void) => Server,
  }
}

我正在尝试将 main 函数与这段 sn-p 代码一起使用:

src/index.js

// @flow
const micro = require("micro")

const server = micro((req, res) => {
  res.end("Hello world!")
})

server.listen(5000)

在该代码 sn-p 中,变量 server、req 和 res 都被键入为 any,即使 micro 变量似乎确实从 libdef 中获取了某种类型。这可以在flow创建的这个coverage report中看到。我尝试了几种不同的方法来定义函数,但似乎没有任何效果。没有发现语法错误,并且似乎找到了 libdef。我做错了什么?

【问题讨论】:

    标签: commonjs flowtype


    【解决方案1】:

    从flow-typed definitions for lru-cache查看这个例子

    简而言之,这应该可以满足您的要求:

    declare module 'micro' {
      declare var exports: (fn: (req: IncomingMessage, res: ServerResponse) => void) => Server;
    }
    

    【讨论】:

    • 类型导入也可能不起作用(我实际上没有尝试您的示例)。试试这个吧。
    • 看来我有两个问题。第一个是可调用对象的错误语法。这可以通过将() 更改为$call 来解决。我想将导出保留为可调用对象,因为 micro 在其上导出其他值。第二个问题是类型导入不起作用。 http 模块类型应该是内置的,所以我不知道为什么它们不起作用。快速绑定像这样导入Server 类型。
    • 很遗憾,我不知道您其他问题的答案。可能值得将其作为一个单独的问题发布。
    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2017-06-13
    • 2018-04-13
    • 1970-01-01
    • 2020-11-11
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多