2017-01-12 19 views
2

我有下面的代碼在我的陣營應用:流動型:條件必需型

import isRequiredIf from 'react-proptype-conditional-require' 

Auth.propTypes = { 
    children: PropTypes.any, 
    step: PropTypes.number, 
    steps: isRequiredIf(PropTypes.number, props => props.hasOwnProperty('step')), 
    footer: PropTypes.any 
} 

這裏steps只有在指定step是必需的。

我將我的React PropTypes遷移到Flow。我能以某種方式實現與Flow相同的行爲嗎?

回答

3

這不能用這種形式的Flow完成。由於PropTypes在運行時被檢查,而不是靜態的,因此可以有更多的靈活性。如果一個靜態typechecker允許這樣的事情,這將是不可判定的。

但是,你可以做這樣的事情:

type Props = { 
    children: any, 
    // not sure about this name, but you get the idea 
    step: ?{ 
    step: number, 
    steps: number, 
    }, 
    footer: any, 
} 

或者,如果你能有steps但不step

type Props = { 
    children: any, 
    // not sure about this name, but you get the idea 
    step: ?{ 
    step?: number, 
    steps: number, 
    }, 
    footer: any, 
} 

顯然,這兩種方法都不是非常的什麼簡明你有,並且需要改變生成和使用這些值的代碼。不幸的是,爲了獲得靜態類型檢測器的安全,有時需要付出代價。

另一種選擇是剛剛離開他們兩個可選:

type Props = { 
    children: any, 
    step?: number, 
    steps?: number, 
    footer: any, 
} 

這樣,流量不會強制執行steps存在,如果存在step。然而,你不需要改變你的其他代碼,也沒有任何東西阻止你添加運行時檢查(這不會比你已經擁有的更糟糕)。