[英]Yup Infertype doesn't work for optional fields
Hi yup's Infertype doesn't work properly for optional fields.嗨,是的,Infertype 不适用于可选字段。
const userSchema = yup.object({
name: yup.string().required(),
age: yup.number().required().positive().integer(),
email: yup.string().email().optional().notRequired(),
website: yup.string().url().nullable(),
createdOn: yup.date().default(() => new Date()),
});
Expected type:预期类型:
/* {
name: string;
age: number;
email?: string | undefined
website?: string | null | undefined
createdOn: Date
}*/
Here is my type:这是我的类型:
Email and website fields are should be optional. Email 和网站字段应该是可选的。
tsconfig.json: tsconfig.json:
"compilerOptions": {
...
"strict": true,
"strictNullChecks": true
}
In the current version of Yup we have solved it using Yup.SchemaOf<Type>
:在当前版本的 Yup 中,我们使用
Yup.SchemaOf<Type>
解决了这个问题:
type User = {
name: string
age: number
email?: string
website?: string | null
createdOn: Date
}
const userSchema: Yup.SchemaOf<User> = object({
name: string().required(),
age: number().required().positive().integer(),
email: string().email(),
website: string().url().nullable(),
createdOn: date().default(() => new Date()),
});
In upcoming versions of Yup you can use InferType
:在即将推出的 Yup 版本中,您可以使用
InferType
:
import { object, string, string, date, InferType } from 'yup';
const userSchema = object({
name: string().required(),
age: number().required().positive().integer(),
email: string().email(),
website: string().url().nullable(),
createdOn: date().default(() => new Date()),
});
type User = InferType<typeof userSchema>;
/* {
name: string;
age: number;
email?: string | undefined
website?: string | null | undefined
createdOn: Date
}*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.