[英]How to validate Date object through io-ts (typescript)?
我還沒有找到這方面的文檔,所以我在這里是 StackOverflow。
我有一個要轉換並用於 io-ts 運行時驗證的接口。 該接口包含一個類型為Date
的字段。 在將io-ts
導入為t
時,我查看了t
上的命令的 rest,但我找不到驗證它是日期的方法
前任:
export interface Transaction {
transactionDate: Date,
phrase: string
}
如何使用 io-ts 將其轉換為類型? 理想情況下,它會是這樣的
export const Transaction = t.type({
transactionDate: t.date,
phrase: t.string
})
我發現唯一可行的方法是將 Date 設置為t.string
類型,但這會讓任何類型的字符串通過。
我發現了一個名為io-ts-types
的 npm package 。 我正在查看文檔,認為它已經是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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.