Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get a list of validated elements #658

Open
mrblond1n opened this issue Aug 31, 2022 · 0 comments
Open

How to get a list of validated elements #658

mrblond1n opened this issue Aug 31, 2022 · 0 comments

Comments

@mrblond1n
Copy link

mrblond1n commented Aug 31, 2022

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant