How to get a list of validated elements
Author: mrblond1nCreated Aug 31, 2022Updated Aug 12, 2024
I have a function that takes codec and data as arguments.
like this
import * as t from 'io-ts';
export const decode = <C extends t.Any>(codec: C, data: unknown): t.TypeOf<C> => {
const either = codec.decode(data);
if (either._tag === 'Right') {
return either.right;
} else {
throw new Error('no matches');
}
};And this function work correctly. For example: I get array of some objects and check via some codec
codec like this
import * as t from 'io-ts';
const ItemDto = t.type({
value: t.string,
id: t.string,
});
export const ItemsCodec = t.array(ItemDto)And if some field to be wrong for example, value is Number type - decode fn throw Error.
However, I want the function to return valid elements from the list.
For example:
const data = [
{
value: 'valid item',
id: '1'
},
{
value: 'not valid item',
id: '2'
}
]
const result = decode(ItemsCodec, data)
/*
* result is [
* {
* value: 'valid item',
* id: '1'
* }
* ]
* */It is possible?
Source: gcanti/io-ts