2017-03-10 42 views
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 

有什麼辦法可以使這項工作?

回答

2

我能夠用較小問題的一小部分重現此問題,我認爲現在我明白了這個問題,因爲它與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 } 

將工作。

+0

你是否有一個使用流類型的'node-fetch'工作示例? – Mbrevda