代码之家  ›  专栏  ›  技术社区  ›  Krisna

Typescript未定义日期验证

  •  1
  • Krisna  · 技术社区  · 4 年前

    我在用 luxon 用于我的应用程序。我有一些未确定的日期。我和你确认我的约会 卢克逊 是的 isDateTime 函数返回字符串。我在应用程序的多个地方使用了这个功能。我传递的大多数地点都是日期字符串,而且只有我得到的地点 undefined 日期我设法消除了打字错误,但我认为这不是最佳解决方案。

    code-sandbox
    有没有更好的方法,我可以实现这个功能?

    const {
      DateTime
    } = require('luxon')
    
    const ISO_DATE_FORMAT = "yyyy-MM-dd";
    
    const dateToStrings = (date: string | number | Date): DateTime =>
      DateTime.fromISO(new Date(date).toISOString());
    
    const dateToISOString = (date: Date | string | undefined): string => { 
      if (DateTime.isDateTime(date)) {
        return dateToStrings(date).toFormat(ISO_DATE_FORMAT);
      }
      return date as string;
    };
    
    console.log(dateToISOString(undefined));
    1 回复  |  直到 4 年前
        1
  •  1
  •   TmTron    4 年前

    在这种情况下 dateToISOString(undefined) ,你只需告诉typescript undefined 是一个字符串,当调用方试图访问字符串值时,它将导致异常。

    相反,你应该处理这个问题 未定义 案例明确,并且(取决于您的用例),您可能希望:

    • 返回默认文本:例如“”、“-”等。
    • 或者抛出一个错误:例如。 throw Error('undefined date!');
    export const dateToISOString = (date: Date | string | undefined): string => {
      if (!date) {
        /**
         * handle the case when the caller passes undefined explicitly.
         * Dependent on your use-case you may want to 
         * - return a default text: e.g. "", "-", etc.
         * - or throw Error('undefined date!');
         */
        return '-';
      } else if (typeof date === "string") {
        // then check if the input is a string
        return date;
      } else {
        /**
         * now typescript knows that the input is of type Date
         * because you defined the input type as:  Date | string | undefined
         * and you have already handled the undefined and string cases
         */
        return dateToStrings(date).toFormat(ISO_DATE_FORMAT);
      }
    };
    
    推荐文章