2017-05-26 32 views
1

我想在外部庫定義中聲明一個組件(我正在編寫流程類型爲react-bootstrap),以便我有可選和必需的道具,並且不需要額外的道具。我有以下幾點:如何在流中指定可選的道具類型?

declare export type AlertProps = {| 
    bsClass: bsClass, 
    bsStyle: ?bsStyle, 
    onDismiss: ?(e: SyntheticEvent) => any, 
    closeLabel: ?string, 
    style: ?style, 
|} 

declare export class Alert extends React$Component { 
    props: AlertProps; 
} 

(在這個例子的目的,讓我們假設bsStyle實際需要),但流仍然抱怨,如果我省略bsClass

49:  props: AlertProps; 
       ^^^^^^^^^^ property `bsClass`. Property not found in 
26:  ? (<Alert bsStyle="danger" style={{ textAlign: 'center' }}> 
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ props of React element `Alert`. See: src/components/audit/AuditAlert.jsx:26 

如果我總結我的道具$Shape<>,我不需要道具。我有一個解決方法如下:

declare export type AlertProps = { 
    // required props go here 
    bsClass: bsClass, 
} & $Shape<{| 
    // all props (optional and required) go here 
    bsClass: bsClass, 
    bsStyle: bsStyle, 
    onDismiss: (e: SyntheticEvent) => any, 
    closeLabel: string, 
    style: style, 
|}> 

但是,這似乎過於hacky!有沒有更好的方法來實現我的目標?

作爲便箋,this question未正確回答。

回答

4

你可以指定一個可選的道具,之後的屬性名稱。例如

​​

我可以忽略optionalString,但如果我通過它,它必須是一個字符串。 maybeString我必須通過,但它的值可以是null,undefined或一個字符串。

您可以在例如here

該文檔談可選對象屬性here用它玩。

相關問題