2017-02-13 92 views
1

說我有一個功能:對象類型flowjs

const example = (item : ?{+type?: ?string}) : {+result: ?string} => { 
    const state = {} 
    state.result = item.result 
    return state 
} 

這失敗,給類型檢查:

12:   state.result = item.result 
            ^^^^^^^ property `result`. Property not found in 
12:   state.result = item.result 
          ^^^^^^ object type 

爲什麼沒有這種類型檢測?我沒有用確切的對象類型符號?{|+type?: ?string|}來定義類型,所以它不應該允許其他鍵嗎?那麼確切的對象符號如何工作呢?我怎樣才能定義這樣的部分對象類型?這甚至有可能嗎?

+0

您的參數'item'沒有名爲'result'的屬性。你是不是要編寫'state.result = item.type'呢? (儘管你還需要在那裏進行空檢查)。 –

+0

如果我的問題不清楚,請隨時編輯。我的意思是這個對象中可能有很多鍵,並不是我可能會列舉的所有鍵,我不明白爲什麼流沒有使用「確切對象」符號來檢查類型。任何方式,我可以澄清這個問題(隨意編輯的方式!) –

回答

1

這聽起來像你試圖編碼的參數item可以有任何屬性的類型。這聽起來像一個地圖,其流量與編碼:

{ [key: KeyType]: ValueType }; 

你舉的例子可以這樣更新:

const example = (item : ?{[key: string]: string}) : {+result: ?string} => { 
    const state = {} 
    if(item) 
    { 
    state.result = item.result; 
    } 
    return state 
} 

注意,你必須做item空校驗,否則它不會typecheck,因爲您在函數簽名中聲明瞭它爲空。

如果有某些必需屬性item那麼您可以使用交集類型來添加該約束。我將爲此創建一個新類型,以便讀取簽名更容易:

type Item = {[key: string]: string} & {type: string} 

const example = (item : ?Item) : {+result: ?string} => { 
    const state = {} 
    if(item) 
    { 
    state.result = item.result; 
    } 
    return state 
} 


example({type: 'blah', x: '2'}); // OK 
example({'blah', x: '2'}); // Error: type is missing 
+0

是否有可能強制項目中的某些鍵的存在,如果存在? –

+0

有一個問題,我仍然不太明白,回答是什麼,如果不是這個,有用的確切對象符號是什麼? –

+0

確切的對象符號是這個部分:'{type:string}'。但我也使用'&'將它與地圖類型結合起來說:它可以具有任何**字符串屬性,但它必須具有'type'屬性。 –