我有一些代码的形式:
interface FormProps {
regexPreset?: RegexPresets;
customRegex?: RegExp;
description?: string;
inputTitle: string;
errorMessage?: string;
}
const Form: React.FC<FormProps> = props => {
return <div> somestuff </div>
}
如果我传入一个customRegex
,我希望编译器在errorMessage
未被传递时抛出一个错误(使errorMessage
成为一个强制属性)。
最接近的是this StackOverflow post,但我不确定是否可以将其应用到我的用例中。
任何指示都将欣然接受。
2条答案
按热度按时间puruo6ea1#
我认为利用您在帖子中提到的内容是可行的,但在进入高级类型之前,我想评估一下最简单的解决方案是否足够。因此,如果您要包含
customRegex
,您将被迫也包含errorMessage
,那么此类型应该涵盖您的用例:wvmv3b1j2#
为了简化,我们假设有以下 prop
这里“inputTitle”属性是强制的,
description
是可选的,但是只有当customRegex
(可选)属性存在时,errorMessage
属性才必须存在(强制的)。创建无条件 prop 的类型
现在,仅当条件属性“customRegex”存在时,才为条件属性创建类型
现在创建一个额外的类型时,条件prop不存在(给予想法的可能值存在于对象)
现在您的FormProps将
以下场景将根据需要给予错误:
以下几种可以: