我最近偶然发现了来自flow-js (https://flow.org/en/docs/types/unions/#disjoint-unions-)的disjoint unions,并尝试在我的React.Component道具中使用它们。
基本的想法是,我有一组道具,总是需要设置的,根据属性,其他一些字段也需要有内容。
在我的示例中,我希望有一个isEditable标志-如果它是真的-还需要设置字段uploadUrl。如果isEditable为false,则uploadUrl必须为空。
// 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]非常感谢你提前!
发布于 2020-01-17 19:28:59
您会得到这个错误,因为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/
https://stackoverflow.com/questions/50392585
复制相似问题