unsplash / sum-types-io-ts

io-ts bindings for @unsplash/sum-types.
https://unsplash.github.io/sum-types-io-ts/
MIT License
2 stars 1 forks source link

`getInternallyTaggedCodec`: decode should preserve tag #25

Closed OliverJAsh closed 10 months ago

OliverJAsh commented 10 months ago
import * as Sum from 'shared/facades/Sum';
import { pipe } from 'shared/facades/function';
import * as t from 'shared/facades/io-ts';

export const FooCodec = t.strict({
  tag: t.literal('Foo'),
  desc: t.string,
});
export interface Foo extends t.TypeOf<typeof FooCodec> {}

export type Template = Sum.Member<'Foo', Foo>;
export const Template = Sum.create<Template>();
export const TemplateCodec = Sum.getInternallyTaggedCodec('tag')(Template)({
  Foo: FooCodec,
});

const a = Template.mk.Foo({ tag: 'Foo', desc: 'bar' });

// This codec law fails: pipe(a, encode, decode) = E.right(a)
// Decode returns Left. This happens because the `tag` property
// is removed before `FooCodec.decode` is called.
console.log(pipe(a, TemplateCodec.encode, TemplateCodec.decode));