我在使用 Yup 验证 typeScript 冲突时在 React Hook Form 中遇到了问题。
假设我们有一个用于编辑和插入(添加新数据)的表单。此表格有
name
和 id
,并且它们都是必需的。所以我们同时制作如下所示的 Yup 模式。
const schema = Yup.object().shape({
name: Yup.string().required(),
id:Yup.number().required(),
})
然后我们应该为反应钩子表单分配值,因为我们有编辑模式。所以我们这样做:
const values = isEditMode ? {name: editValue.name , id: editValue.id} : {name: '', id: null}
这里我们就要面临问题了。名称不能是
null
,因为我们将其设为必需。我不能保留它,也不把它写在值中,因为它会是undefined
,我们会再次收到错误。也不能给它一个像 -1 这样的虚拟数字或在 schema 中创建 id nullable()
,因为虽然 typeScript 错误会消失,但如果用户忘记填写 Id 输入,那么它不会显示验证错误它是必需的,因为它的值为 -1,或者它可以是 null
。
在这种情况下我应该做什么来解决值解析器的 typeScript 错误,同时验证也工作正常。
所以我找到了一种不寻常的方法来解决它。
const schema = Yup.object().shape({
name: Yup.string().required(),
id:Yup.number().required()nullable().notOneOf([null] , 'the id is required'),
})
通过这种方式,我们添加
nullable()
,以便 typeScript 允许初始 null
值。
然后通过使用
notOneOf([null] , 'the id is required')
我们说在提交表单时该值不能为 null
,如果为空则显示错误消息。