枚举:“"HH:MM"”类型的参数不可分配给 'FormatOptions' 类型的参数

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

我创建了一个接受两个参数数据和格式的函数。我正在尝试为名为“格式”的参数创建 ENUM(FormatOptions)。但是,这里有一个错误:

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

如何为第二个参数编写正确的 ENUM? 这是 TypeScript 上的 Playground Click

代码:

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

您可以使用 union:

而不是 enum
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');