【发布时间】: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