区分 TypeScript 中的仅日期和"Date"日期+时间类型



我想使用TypeScript类型系统来区分只表示日期(没有时间成分(的变量和Date这样类型的变量,后者可以表示带时间的日期("日期-时间"值(。

我当然知道Date可以表示日期,但如果不区分类型系统,我认为我更有可能混淆我对日期和日期时间的意图。

做出这种区分的系统的一个例子是Python日期时间库,它同时具有datedatetime类型https://docs.python.org/3/library/datetime.html

例如(但API不需要完全像这样(:

const date: OnlyDate = makeOnlyDate()
const datetime: Date = new Date()
date + datetime  // type error: perhaps Operator '+' cannot be applied to types 'OnlyDate' and 'Date'
let datetime2: Date = date  // type error: perhaps Type 'OnlyDate' is not assignable to type 'Date'
let date2: OnlyDate = datetime  // type error: perhaps Type 'Date' is not assignable to type 'OnlyDate'
date.getSeconds  // type error: Property 'getSeconds' does not exist on type ...

我该怎么做?理想情况下不亲自实施(即标准解决方案是理想的(?

我认为你不太喜欢的谷歌术语是";日历日期类型";。有几个库为Typescript提供了这种类型。看起来它正在进行更积极的开发(这并不是一个奇怪的选择——详见下文(是日历日期。

另一个选项是键入日历日期,但它将月份表示为三个字符的字符串,我觉得这很不幸。

最新更新