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

add withEncode function #146

Closed EricCrosson closed 3 years ago

EricCrosson commented 3 years ago

withEncode is similar to withValidate:

withEncode clones an existing codec and overrides the existing encode function with the given encode function. This can be useful when you want to use t.type to combinatorially create codecs but want to leverage the encode function to encode into a different type.

gcanti commented 3 years ago

Thanks @EricCrosson, I would add an optional name argument though:

export function withEncode<A, O, I, P>(
  codec: t.Type<A, O, I>,
  encode: (a: A) => P,
  name: string = codec.name
): t.Type<A, P, I> {
  return new t.Type(name, codec.is, codec.validate, encode)
}
EricCrosson commented 3 years ago

Excellent! That's a much better implementation too. Thanks for the suggestion @gcanti , I've pushed these updates to the PR