簡體   English   中英

是的。當使用 typescript 進行驗證時

[英]Yup .when validation with typescript

我正在將驗證模式從jsx轉換為tsx文件類型。 它在jsx中完美運行,但在tsx中, when條件通過時,我無法獲得 yup 的類型。 甚至any沒有通過。 知道如何正確輸入嗎? 出現的錯誤是

Argument of type '(startTime: Date) => Yup.DateSchema<Date | undefined, Record<string, any>, Date | undefined> | undefined' is not assignable to parameter of type 'ConditionOptions<RequiredDateSchema<Date | undefined, Record<string, any>>>'.

Type '(startTime: Date) => Yup.DateSchema<Date | undefined, Record<string, any>, Date | undefined> | undefined' is not assignable to type 'ConditionBuilder<RequiredDateSchema<Date | undefined, Record<string, any>>>'.

Type 'DateSchema<Date | undefined, Record<string, any>, Date | undefined> | undefined' is not assignable to type 'SchemaLike'. Type 'undefined' is not assignable to type 'SchemaLike'. TS2345

我的驗證:

Yup.date().required('This field is required')
            .when('startTime', (startTime: Date) => { // <-- this is where error appears
                if (startTime) {
                    return Yup.date()
                        .min(startTime, 'End must be after Start')
                        .typeError('End is required')
                }
            }),

最簡單的事情:

Yup.date().required('This field is required')
            .when('startTime', (startTime: Date) => {
                if (startTime) {
                    return Yup.date()
                        .min(startTime, 'End must be after Start')
                        .typeError('End is required')
                } 
                return Yup.date()
            })

我個人更喜歡:

Yup.date()
  .required("This field is required")
  .when("startTime", (startTime) =>
    startTime
      ? Yup.date()
          .min(startTime, "End must be after Start")
          .typeError("End is required")
      : Yup.date()
  );

但這只是清理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM