When it comes to simplicity, using the Decoder approach with io-ts
has proven to be effective:
import { isRight } from 'fp-ts/Either';
import * as D from 'io-ts/Decoder';
const thing = D.struct({
id: D.number,
createdAt: D.string,
});
export const isValidThing = (candidate: unknown): boolean =>
isRight(thing.decode(candidate));
However, I am now looking to enhance date validation. I thought I could do something like this:
import { DateFromISOString } from 'io-ts-types/lib/DateFromISOString';
const thing = D.struct({
id: D.number,
createdAt: DateFromISOString
});
but it's not as straightforward as I had hoped:
ERROR: src/middleware/validators/event.ts:7:3 - error TS2322: Type 'DateFromISOStringC' is not assignable to type 'Decoder<unknown, Date>'.
The types returned by 'decode(...)' are incompatible between these types.
Type 'Validation<Date>' is not assignable to type 'Either<DecodeError, Date>'.
Type 'Left<Errors>' is not assignable to type 'Either<DecodeError, Date>'.
Type 'Left<Errors>' is not assignable to type 'Left<DecodeError>'.
Type 'Errors' is not assignable to type 'DecodeError'.
Type 'ValidationError[]' is missing the following properties from type 'Concat<DecodeError<string>>': _tag, left, right
createdAt: DateFromISOString
It seems there was a misunderstanding on my part. Is there a more straightforward way to validate dates using decoders and struct
?
Edit: It should be noted that this method does work with the older, non-experimental approach:
import * as t from 'io-ts';
import { DateFromISOString } from 'io-ts-types';
const thing = t.type({
id: t.number,
createdAt: DateFromISOString
});