Skip to content

Instantly share code, notes, and snippets.

@tonyonodi
Last active December 5, 2021 23:47
Show Gist options
  • Save tonyonodi/d6955bb8a54339f2265285d070f970c5 to your computer and use it in GitHub Desktop.
Save tonyonodi/d6955bb8a54339f2265285d070f970c5 to your computer and use it in GitHub Desktop.
Compose io-ts Codecs
export const compose = <Name extends string, I2, A extends I2, B, I1, O1>(
name: Name,
Codec1: t.Type<A, O1, I1>,
Codec2: t.Type<B, A, I2>
): t.Type<B, O1, I1> => {
return new t.Type<B, O1, I1>(
name,
(u): u is B => Codec2.is(u),
(a, c) =>
pipe(
a,
(a) => Codec1.validate(a, c),
chain((b) => Codec2.validate(b, c))
),
(b) => pipe(b, Codec2.encode, Codec1.encode)
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment