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

[io-ts-extra] Question about Mapper interface's generic args #246

Open
martaver opened this issue Nov 13, 2021 · 1 comment
Open

[io-ts-extra] Question about Mapper interface's generic args #246

martaver opened this issue Nov 13, 2021 · 1 comment

Comments

@martaver
Copy link

martaver commented Nov 13, 2021

Hi,

I'm happily using io-ts-extra to aid in my type-iness so thanks for taking the time to publish your library!

One of the things I really like is the mapper/parser interface that you've set up. I'm trying to nest parser codecs inside more complex types, and found a problem when trying to create a parser of a type that contains a parser type nested within it.

A contrived example:

// Given a codec for an array of numbers.
const arr = t.array(t.number);

// Define a parser for it.
const arr_string = t.parser(arr, s => s as any, s => s as any);
// E.g.
arr_string.decode('1,2');

// Define an object with an array of numbers as property,
// but will decode/encode that property as a string.
const obj = t.type({
  myArr: arr_string
})
// E.g.
obj.decode({ myArr: '1,2' })

// Define a parser forit
const obj_string = t.parser(obj, s => s as any, s => s as any);
obj_string.decode('{ "myArr": "1,2" }');

In the above, the codecs function correctly, however Typescript will complain about obj in const obj_string = t.parser(obj, ...); with (abbreviated)

Types of property 'is' are incompatible.

After some digging, I noticed that the Mapper interface expects the codec's actual type ToA to inherit from it output type ToO.

The reason the Mapper complains about using the parser as From is because the parser's ToO is now string, which obviously doesn't extend number[].

My question to you is why does the Mapper interface constrain ToA extends ToO? The original t.Type<A, O, I> has no such constraint.

Would it be safe to remove this constraint, since it prevents the harmonious nesting of mapper/parser types?

@martaver
Copy link
Author

martaver commented Nov 13, 2021

Check out my PR for my fix, which implements support for nested mappers / parsers:
#248

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