typescript 如何导入DateTimeFormatOptions

kcrjzv8t  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(164)

我想为date.toLocaleString()存储一个DateTimeFormatOptions,以便在我的应用程序中的多个位置使用。我定义了它:

export const timeFormat = { month: 'numeric', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false, timeZoneName: 'short', time  Zone: 'UTC'}

我得到:

Argument of type '{ month: string; day: string; hour: string; minute: string; hour12: boolean; timeZoneName: string; timeZone: string; }' is not assignable to parameter of type 'DateTimeFormatOptions'.
  Types of property 'month' are incompatible.
    Type 'string' is not assignable to type '"numeric" | "2-digit" | "short" | "long" | "narrow" | undefined'.

但是我不知道import DateTimeFormatOptions是什么意思,最后我只是写了一个帮助器方法来格式化日期,但是我仍然需要导入它,因为我可能允许用户更改日期偏好。

nbnkbykc

nbnkbykc1#

它在Intl对象中。您不需要导入它。只需将类型设置为Intl.DateTimeFormatOptions

const timeFormat: Intl.DateTimeFormatOptions = { 
  month: 'numeric',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  hour12: false,
  timeZoneName: 'short',
  timeZone: 'UTC'
}

相关问题