如何在流程中指定可选的道具类型?

How do I specify optional prop types in flow?

我想在外部库定义中声明一个组件(我正在为 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,
|}>

然而,这似乎过于骇人听闻了!有没有更好的方法来实现我的目标?

作为旁注, 没有正确回答。

您可以通过放置 ?在 属性 名称之后。例如

type Props = {
  optionalString?: string,
  maybeString: ?string,
}

我可以省略optionalString,但如果我传递它,它必须是一个字符串或未定义。 maybeString 我必须传递,但它的值可以是 null、undefined 或字符串。

你可以在示例中使用它here

文档讨论了可选的对象属性 here