我想在外部库定义中声明一个组件(我正在为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,
|}>
但是,这似乎过于苛刻!有没有更好的方法来实现我的目标?
作为旁注,this question没有正确回答。