zaq*_*zaq 6 validation typescript reactjs yup formik
我使用以下电话号码验证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
})
})
Run Code Online (Sandbox Code Playgroud)
错误
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
Run Code Online (Sandbox Code Playgroud)
以下是类型定义phone
type AvailableLanguage = "fi" | "en"
export interface CreateUserForm {
firstName: string
lastName: string
email: string
phone: string
language: AvailableLanguage
}
Run Code Online (Sandbox Code Playgroud)
由于最近的变更日志中有重大更改。我不确定幕后发生了什么
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
})
})
Run Code Online (Sandbox Code Playgroud)
我不确定该属性是否phone应该允许undefined(使用?),但我认为您也可以将其作为stringonly like传递(phone: string)。
也许你想知道:
可能是因为旧版本对打字稿的支持不太好,而在新版本中,他们“修复”了打字稿或用打字稿做了更好的东西。
| 归档时间: |
|
| 查看次数: |
8534 次 |
| 最近记录: |