1
我想要做的就是包裝fetch
函數來處理一些fetch
樣板,如調用.json()
。FlowType在不丟失默認類型註釋的情況下提取
問題是,如果我用自己的註釋包裝了fetch
函數,那麼我會失去很多類型安全性,因爲我的類型永遠不會像默認情況下的Flow類型那樣具體。
於是,我就採取生存類型(*)
和typeof
的優勢,使流量保持默認註釋
// 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
有什麼辦法可以使這項工作?
你是否有一個使用流類型的'node-fetch'工作示例? – Mbrevda