我最近偶然发现了来自flow-js(https://flow.org/en/docs/types/unions/#disjoint-unions-)的disjoint unions
,并尝试在我的React.Component
道具中使用它们。
基本的想法是我有一套总是需要设置的道具,根据属性,其他一些领域也需要有内容。
在我的示例中,我想要一个isEditable
标记 - 如果它是真的 - 还需要设置字段uploadUrl
。如果isEditable
为false,则uploadUrl
必须为null。
// Base properties
type OverallProps = { imageUrl: string, username: string };
// Disjoint unions
type IsPlainProps = { isEditable: false, uploadUrl: null };
type IsEditableProps = { isEditable: true, uploadUrl: string };
// My Props
type Props = OverallProps & (IsPlainProps | IsEditableProps);
不幸的是,我无法使用此设置并且我不知道为什么。
有人可以向我解释为什么我会收到以下错误吗?
<Something
^ Cannot create `Something` element because: Either boolean [1] is incompatible with boolean literal `false` [2] in property `isEditable`. Or boolean [1] is incompatible with boolean literal `true` [3] in property `isEditable`.
References:
23: const isEditable: bool = true;
^ [1]
9: isEditable: false,
^ [2]
14: isEditable: true,
^ [3]
提前非常感谢!
答案 0 :(得分:0)
您会收到此错误,因为true和false是值。
您正在定义数据类型,例如这样做:
import * as React from 'react';
type OverallProps = {
imageUrl: string,
username: string,
};
type IsPlainProps = {
isEditable: bool,
uploadUrl: ?string,
};
type IsEditableProps = {
isEditable: bool,
uploadUrl: string,
};
type Props = OverallProps & (IsPlainProps | IsEditableProps);
class Something extends React.PureComponent<Props> {
}
const isEditable: bool = true;
<Something
imageUrl="abc"
username="username"
isEditable={isEditable}
uploadUrl={isEditable ? "uploadUrl" : null}
/>
您还在为这个问题苦苦挣扎吗?要根据给定的值更改数据结构的类型,也许铸造是正确的解决方案? https://flow.org/en/docs/types/casting/