打字稿未定义的日期验证

Typescript undefined date validation

我正在使用 luxon for my app. I have some undefined date. I validate my date with luxonisDateTime 和函数 returns 字符串。我在应用程序的多个地方使用了这个功能。大多数我传递日期字符串的地方,只有我得到 undefined 日期的地方。我设法消除了 Typescript 错误,但我认为这不是最佳解决方案。

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));

在这种情况下 dateToISOString(undefined),您只需告诉打字稿 undefined 是一个字符串,稍后当调用者尝试访问 string-value.[=15= 时会导致异常]

相反,您应该明确处理 undefined 情况,并且(取决于您的 use-case)您可能需要:

  • return 默认文本:例如“”、“-”等
  • 或抛出错误:例如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);
  }
};