【问题标题】:FlowType wrapping fetch without losing default type annotationsFlowType 包装 fetch 而不会丢失默认类型注释
【发布时间】:2017-07-31 06:24:11
【问题描述】:

我想做的是包装fetch 函数来处理一些fetch 样板,例如调用.json()

但问题是,如果我将 fetch 函数包装在一个带有我自己注释的函数中,我会失去很多类型安全性,因为我的类型永远不会像 Flow 默认情况下那样具体.

所以我尝试利用存在类型 (*)typeof 让 Flow 保持默认注释

// Imported as f because importing as "fetch"
// overwrites all of Flow's default type info about fetch
import f from 'node-fetch'

export const fetchJSON: typeof fetch =
  (url: *, opts: *): * => f(url, opts).then(r => r.json())

export const post: typeof fetchJSON = (url: *, opts: *): * => fetchJSON(url, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  ...opts
})

不幸的是,这给了我一些没有多大意义的类型错误

 10: export const post: typeof fetchJSON = (url: *, opts: *): * => fetchJSON(url, {
                                                                                  ^ object literal
 11:   method: 'POST',
               ^^^^^^ string. This type is incompatible with
824:     method?: ?MethodType;
                  ^^^^^^^^^^^ null. See lib: /private/tmp/flow/flowlib_22594590/bom.js:824

x.js:10
 10: export const post: typeof fetchJSON = (url: *, opts: *): * => fetchJSON(url, {
                                                                                  ^ object literal
 12:   headers: { 'Content-Type': 'application/json' },
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ object literal. This type is incompatible with
822:     headers?: ?HeadersInit;
                   ^^^^^^^^^^^^ null. See lib: /private/tmp/flow/flowlib_22594590/bom.js:822

x.js:10
 10: export const post: typeof fetchJSON = (url: *, opts: *): * => fetchJSON(url, {
                                                                                  ^ object literal
 12:   headers: { 'Content-Type': 'application/json' },
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ property `Content-Type`. Property not found in
822:     headers?: ?HeadersInit;
                    ^^^^^^^^^^^ Headers. See lib: /private/tmp/flow/flowlib_22594590/bom.js:822


Found 3 errors

有什么办法可以做到吗?

【问题讨论】:

    标签: javascript node.js types flowtype


    【解决方案1】:

    我能够用更大问题的一小部分来重现这个问题,我想我现在理解了这个问题,因为它与fetch 本身完全无关。

    // @flow
    const opts: RequestOptions = {}
    const test = { method: 'POST', headers: { 'Content-Type': 'application/json' }, ...opts }
    

    上述导致类似的错误,这是因为将opts 传播到对象中可能会将'POST' 重写为null,这是不允许的,因为它具有string 类型。解决方案是传播到一个新的对象,而不是现有的。所以

    const test = { ...{ method: 'POST', headers: { 'Content-Type': 'application/json' } }, ...opts }
    

    会起作用的。

    【讨论】:

    • 你有node-fetch 使用流类型的工作示例吗?
    猜你喜欢
    • 2016-12-07
    • 2019-04-13
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多