使用最新版本 0.29.3 对字符串类型进行 Formik 和 yup 验证

Formik and yup validation on string type using latest release 0.29.3

我使用 yup 进行了以下 phone 号码验证,但升级后出现 TS 错误

"yup": ^0.27.0"yup": "^0.29.3"

"@types/yup": "^0.26.27""@types/yup": "^0.29.7"

const ValidationSchema = Yup.object().shape<ICreateUserForm>({
  phone: Yup.string()
    .required("Required")
    .test("countryCode", "Must include country code", (phone?: string) => {
      return !!phone && phone.startsWith("+")
    })
    .test("isValidNumber", "Must be valid phonenumber", (phone?: string) => {
      const parsedNumber = !!phone && parsePhoneNumberFromString(phone)
      return parsedNumber && parsedNumber.isValid() ? true : false
    })
})

错误

No overload matches this call.
  Overload 1 of 4, '(name: string, message: TestOptionsMessage<{}, any>, test: TestFunction<string | null | undefined, object>): StringSchema<string, object>', gave the following error.
    Argument of type '(phone?: string | undefined) => boolean' is not assignable to parameter of type 'TestFunction<string | null | undefined, object>'.
      Types of parameters 'phone' and 'value' are incompatible.
        Type 'string | null | undefined' is not assignable to type 'string | undefined'.
          Type 'null' is not assignable to type 'string | undefined'.
  Overload 2 of 4, '(name: string, message: TestOptionsMessage<{}, any>, test: AssertingTestFunction<string, object>): StringSchema<string, object>', gave the following error.
    Argument of type '(phone?: string | undefined) => boolean' is not assignable to parameter of type 'AssertingTestFunction<string, object>'.
      Signature '(phone?: string | undefined): boolean' must be a type predicate.  TS2769

以下是phone

的类型定义
type AvailableLanguage = "fi" | "en"

export interface CreateUserForm {
  firstName: string
  lastName: string
  email: string
  phone: string
  language: AvailableLanguage
}

由于最近的更新日志中有 bo 重大更改。我不确定幕后发生了什么

https://github.com/jquense/yup/blob/master/CHANGELOG.md https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yup

问题在于如何在传递给 .test 的函数中声明参数类型。

您正在传递 (phone?: string),但它需要是 (phone?: string | null),因为错误提到。

这是它应该如何工作

const ValidationSchema = Yup.object().shape<ICreateUserForm>({
  phone: Yup.string()
    .required("Required")
    .test("countryCode", "Must include country code", (phone?: string | null) => {
      return !!phone && phone.startsWith("+")
    })
    .test("isValidNumber", "Must be valid phonenumber", (phone?: string | null) => {
      const parsedNumber = !!phone && parsePhoneNumberFromString(phone)
      return parsedNumber && parsedNumber.isValid() ? true : false
    })
})

我不确定 属性 phone 是否应该允许 undefined(使用 ?),但我认为您也可以将其作为 string 只喜欢 (phone: string).

也许您想知道:

为什么我在升级后收到此打字稿错误?

可能是因为旧版本对 typescript 的支持不够好,在新版本中,他们“修复”了 typescript 或改进了 typescript。

我遇到了类似的问题,通过安装 Yup 包和@types/yup 包的最新版本 解决了这个问题。

npm i -S yup@0.32.8
npm i -D @ types/yup@0.29.11

我在 Repl.it 上做了一个测试: [https://repl.it/join/ytnxoyno-jefferson1919]