Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Date object through io-ts (typescript)?

I haven't been able to find documentation on this, so here I am StackOverflow.

I have an interface that I want to convert and use in io-ts' run-time validation. This interface includes a field with type Date on it. I've looked through the rest of the commands on t when importing io-ts as t and I can't find a way to validate that it's a date

Ex:

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

How do I convert this into a type using io-ts? Ideally it would be something like this

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

The only thing that I've found that works is setting the Date as type t.string, but that would let any kind of string through.

like image 560
jdlam Avatar asked Sep 12 '25 16:09

jdlam


1 Answers

I found an npm package called io-ts-types. I was looking at the documentation thinking it was part of io-ts already.

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

There's a module built into io-ts-types dedicated to dates

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

Example of usage

import * as td from 'io-ts-types'

const dateObj = t.type({
  date: td.date
})

const test = {
  date: new Date()
}

You can use the decoder to validate that this works like so isLeft(dateObj.decode(test))

like image 164
jdlam Avatar answered Sep 14 '25 05:09

jdlam