Home > Mobile >  ENUM: Argument of type '"HH:MM"' is not assignable to parameter of type 'Fo
ENUM: Argument of type '"HH:MM"' is not assignable to parameter of type 'Fo

Time:06-03

I made a function that accepts two arguments data and format. I'm trying to make ENUM(FormatOptions) for argument called "format". However, here is an error:

Argument of type '"HH:MM"' is not assignable to parameter of type 'FormatOptions'

How to write the correct ENUM for 2nd argument? Here is Playground on TypeScript Click

Code:

const basicTime: any = {
  year: 'numeric',
  month: 'short',
  day: '2-digit',
  hour: 'numeric',
  minute: 'numeric',
};

const hoursMinutes: any = {
  hour: 'numeric',
  minute: 'numeric',
};

enum FormatOptions {
  HoursMinutes = 'HH:MM',
  MonthDayYear = 'MM/DD/YYYY',
};

const dateFormat = (date: Date, format: FormatOptions) => {
  if (format === 'HH:MM') {
    return new Date(date).toLocaleString('en-US', hoursMinutes);
  }

  return new Date(date).toLocaleString('en-US', basicTime);
};

dateFormat(new Date, 'HH:MM');

CodePudding user response:

Instead of enum you can use union:

const basicTime: Intl.DateTimeFormatOptions = {
  year: 'numeric',
  month: 'short',
  day: '2-digit',
  hour: 'numeric',
  minute: 'numeric',
};

const hoursMinutes: Intl.DateTimeFormatOptions = {
  hour: 'numeric',
  minute: 'numeric',
};


type FormatOptions = 'HH:MM' | 'MM/DD/YYYY'


const dateFormat = (date: Date, format: FormatOptions) => {
  if (format === 'HH:MM') {
    return new Date(date).toLocaleString('en-US', hoursMinutes);
  }

  return new Date(date).toLocaleString('en-US', basicTime);
};

dateFormat(new Date(), 'HH:MM');

  • Related