问题描述
"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]