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

问题描述

我使用yup进行了以下电话号码验证,但升级后出现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,test: AssertingTestFunction<string,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(使用?),但是我认为您也可以像{ {1}}。

也许您在想:

为什么升级后出现此打字稿错误?

可能是因为旧版本不支持出色的打字稿,而在新版本中,他们“修复”了打字稿或使打字稿变得更好。

,

我遇到了类似的问题,并通过安装 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]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...