我定义了这个Yup模式:
export const ExpectedIncomeSchema = object({
newIncome: number()
.required()
.typeError()
.min(0)
.integer(),
fromDate: date()
.required()
.typeError()
.min(startOfToday()),
});
export type ExpectedIncomeValues = Asserts<typeof ExpectedIncomeSchema>;
现在,我试图在react-hook-form
中使用此模式进行验证,并遇到了一个问题,即不允许将defaultValues
设置为null
或""
。很明显,因为类型记录说这里唯一允许的类型是number
和Date
,但我不想将这些值默认为有效值,比如0
或随机选择的日期。我希望这些字段最初是空的。
const methods = useForm<ExpectedIncomeValues>({
resolver: yupResolver(ExpectedIncomeSchema),
defaultValues: {
newIncome: null, // <-- only number allowed, so type error in both Typescript and validation
fromDate: null, // <-- only Date allowed, so type error in both Typescript and validation
},
);
怎么才能让Yup和打字稿在这里都开心呢?在设置表单时,我希望字段是可空的,但在模式验证之后则不需要。
对此,你有什么聪明的地方吗?还是我必须这样做?
export type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
export type ExpectedIncomeFormValues = Nullable<ExpectedIncomeValues>;
但是,这方面的一个问题是,错误消息将是“类型错误”消息,而不是我在本例中需要的“必需”消息。
发布于 2022-06-14 04:58:39
下面的内容似乎有效,但不确定它是否真的正确。我意识到yup
有两种类型的帮助,TypeOf
和Asserts
.通过将.nullable(true)
添加到模式中,第一个将允许null
,而第二个将不允许。这就是我想要的。
const schema = object({
newIncome: number()
.required()
.nullable(true)
.min(0)
.integer(),
fromDate: date()
.required()
.nullable(true)
.min(startOfToday()),
});
type ValuesWithNull =
TypeOf<typeof ExpectedIncomeSchema>;
type ValuesWithoutNull =
Asserts<typeof ExpectedIncomeSchema>;
https://stackoverflow.com/questions/72599238
复制相似问题