【问题标题】:How to validate Date object through io-ts (typescript)?如何通过 io-ts (typescript) 验证 Date 对象?
【发布时间】:2021-05-31 12:25:21
【问题描述】:

我找不到这方面的文档,所以我在这里是 StackOverflow。

我有一个要转换并用于 io-ts 运行时验证的接口。该接口包含一个类型为Date 的字段。将io-ts 导入为t 时,我查看了t 上的其余命令,但我找不到验证日期的方法

例如:

export interface Transaction {
  transactionDate: Date,
  phrase: string
}

如何使用 io-ts 将其转换为类型?理想情况下是这样的

export const Transaction = t.type({
  transactionDate: t.date,
  phrase: t.string
})

我发现唯一可行的方法是将日期设置为类型t.string,但这会让任何类型的字符串通过。

【问题讨论】:

    标签: javascript typescript validation runtime typing


    【解决方案1】:

    我发现了一个名为 io-ts-types 的 npm 包。我在查看文档时认为它已经是 io-ts 的一部分。

    https://github.com/gcanti/io-ts-types

    io-ts-types 内置了一个专门用于日期的模块

    https://gcanti.github.io/io-ts-types/modules/date.ts.html

    使用示例

    import * as td from 'io-ts-types'
    
    const dateObj = t.type({
      date: td.date
    })
    
    const test = {
      date: new Date()
    }
    

    您可以使用解码器来验证它是否像这样isLeft(dateObj.decode(test))

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多