reactjs Yup:何时迁移到1.0.2

5anewei6  于 2023-03-22  发布在  React
关注(0)|答案(1)|浏览(108)

给定一个React状态变量

const [selectedFormtype, setSelectedFormtype] = useState<Nullable<MyFormTypeVm>>()

类型/接口是这样定义的

type Nullable<T> = T | null

interface MyFormTypeVm {
    readonly id: NonNullable<string>
    readonly labelCompanyId: Nullable<string>
}

interface MyFormVm {
    companyId: Nullable<string>
    // remaining properties goes here
}

我用yup找到了一个可行的解决方案:0.32.11。

const validationSchema: yup.SchemaOf<MyFormVm> = yup.object().shape({
    companyId: yup.string().when([], {
        is: () => selectedFormtype?.labelCompanyId,
        then: yup.string()
            .required('Company-id is required')
            .matches(/^[8|9]\d{8}$/i, 'Company-id has to start with 8 or 9')
    })
).required()

我可以从here中看到如何实现引用验证范围中另一个字段的when

string()
-   .when('other', function (other) => {
-      if (other) return this.required()
+   .when('other', ([other], schema) => {
+     return other ? schema.required() : schema
  })

根据迁移指南,我的validationSchema的大纲应该是这样的,但是它给了我一个TS 2322-error。

const validationSchema: yup.ObjectSchema<MyFormVm> = yup.object().shape({
        companyId: yup.string().when('other', ([], schema) => {
            return selectedFormtype?.labelCompanyId
                ? schema
                      .required('required text goes here')
                      .matches(/^[8|9]\d{8}$/i, 'regex text goes here')
                : schema
        })
})

我在tsconfig.json中添加了以下内容:
“严格空检查”:true,“strictFunctionTypes”:假的

41zrol4v

41zrol4v1#

最后在文档中找到了解决这个问题的方法。.default<Nullable<string>>(null)解决了从string | null | undefinedstring | null的转换。

const validationSchema: yup.ObjectSchema<MyFormVm> = yup.object().shape({
    companyId: yup.string().default<Nullable<string>>(null).when(([], schema) =>
        selectedFormtype?.labelCompanyId
            ? schema
                .required('required msg goes here')
                .matches(/^[8|9]\d{8}$/i, 'regex msg goes here')
            : schema.nullable()
    )
})

相关问题