reactjs 如何根据另一个正在通过的 prop 使 prop 成为强制 prop

oxf4rvwz  于 2022-12-22  发布在  React
关注(0)|答案(2)|浏览(161)

我有一些代码的形式:

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,但我不确定是否可以将其应用到我的用例中。
任何指示都将欣然接受。

puruo6ea

puruo6ea1#

我认为利用您在帖子中提到的内容是可行的,但在进入高级类型之前,我想评估一下最简单的解决方案是否足够。因此,如果您要包含customRegex,您将被迫也包含errorMessage,那么此类型应该涵盖您的用例:

interface FormProps {
  regexPreset?: RegexPresets;
  description?: string;
  inputTitle: string;
  customRegexProps?: {
    customRegex: RegExp;
    errorMessage: string;
  }
}
wvmv3b1j

wvmv3b1j2#

为了简化,我们假设有以下 prop

interface FormProps {
  inputTitle: string;
  description?: string;
  
  customRegex?: string;
  errorMessage: string;
}

这里“inputTitle”属性是强制的,description是可选的,但是只有当customRegex(可选)属性存在时,errorMessage属性才必须存在(强制的)。
创建无条件 prop 的类型

interface FormMainProps {
  description?: string;
  inputTitle: string;
}

现在,仅当条件属性“customRegex”存在时,才为条件属性创建类型

interface FormErrorProps {
  customRegex: string; 
  errorMessage: string;
}

现在创建一个额外的类型时,条件prop不存在(给予想法的可能值存在于对象)

interface FormErrorRefProps {
  customRegex?: undefined; 
  errorMessage?: never; 
  // important step; so if customRegex prop is not present errorMessage should not be there and vice-versa
}

现在您的FormProps将

type FormProps =  FormMainProps & (FormErrorProps | FormNotErrorProps);

以下场景将根据需要给予错误:

let a: FormProps;

a = {
  inputTitle: "Title",
  customRegex: "asdasd"
};

/*
Type '{ inputTitle: string; customRegex: string; }' is not assignable to type 'FormProps'.
Type '{ inputTitle: string; customRegex: string; }' is not assignable to type 'FormMainProps & FormErrorProps'.
    Property 'errorMessage' is missing in type '{ inputTitle: string; customRegex: string; }' but required in type 'FormErrorProps'.ts(2322)
*/

a = {
  inputTitle: "Title",
  errorMessage: "asdasd"
};

/*
Type '{ inputTitle: string; errorMessage: string; }' is not assignable to type 'FormProps'.
Type '{ inputTitle: string; errorMessage: string; }' is not assignable to type 'FormMainProps & FormNotErrorProps'.
    Property 'customRegex' is missing in type '{ inputTitle: string; errorMessage: string; }' but required in type 'FormNotErrorProps'.
*/

以下几种可以:

a = {
  inputTitle: "Title",
  errorMessage: "asdasd",
  customRegex: "Title",
};

a = {
  inputTitle: "Title"
};

相关问题