gcanti / io-ts-types

A collection of codecs and combinators for use with io-ts
https://gcanti.github.io/io-ts-types/
MIT License
311 stars 40 forks source link

allow withFallback to accept a function #103

Closed jamiehodge closed 2 years ago

jamiehodge commented 5 years ago

To support, for example, withFallback(UUID, () => uuid()).

mlegenhausen commented 5 years ago

Just a side note but uuid is not a pure function so the example IMHO illustrates a wrong usecase of a lazy withFallback version.

lauritzsh commented 5 years ago

@mlegenhausen What's wrong with an impure function here and how would you instead structure it? I would use it for exactly the same use case as Jamie.

mlegenhausen commented 5 years ago

Normally I would expect impure code to run in something IO or Task related. Until now running Decoder.decode(someType) resulted always in the same result (pure). Using uuid in this context changes the behavior.

My solution for this problem would be to extract the impurity. For example the uuid package allows to provide all parameters that result in the uuid to be passed via an options parameter.

const mkCodec = (uuidOptions) => t.interface({
  id: withFallback(UUID, uuid(uuidOptions))
  ...
})
mlegenhausen commented 5 years ago

Maybe the discussion goes beyond the io-ts field. When you use io-ts without fp-ts this usage with a side effectful function seems reasonable.