Home > OS >  Typescript undefined date validation
Typescript undefined date validation

Time:02-12

I am using luxon for my app. I have some undefined date. I validate my date with luxon's isDateTime and function returns string. I used this function multiple places of the app. Most of the places I am passing date string and only places I am getting undefined date. I manage to silent the Typescript error but I think it's not optimal solution.

code-sandbox
Is there any better way, I can make this function?

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

CodePudding user response:

In this case dateToISOString(undefined), you simply tell typescript that undefined is a string, which will later cause exceptions when the caller tries to access the string-value.

Instead you should handle the undefined case explicitly and (dependent on your use-case) you may want to:

  • return a default text: e.g. "", "-", etc.
  • or throw an error: e.g. 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);
  }
};
  • Related