Skip to content

Instantly share code, notes, and snippets.

@Magellol
Created February 7, 2024 22:38
Show Gist options
  • Save Magellol/36b00fe158c414253d5ffa6726d873be to your computer and use it in GitHub Desktop.
Save Magellol/36b00fe158c414253d5ffa6726d873be to your computer and use it in GitHub Desktop.
Derive sum types from codecs
import * as Sum from 'shared/facades/Sum';
import * as t from 'shared/facades/io-ts';
const TypeA = t.strict({
a: t.string,
});
interface TypeA extends t.TypeOf<typeof TypeA> {}
const TypeB = t.strict({
b: t.number,
});
interface TypeB extends t.TypeOf<typeof TypeB> {}
// ------------------------
// Version 1
// ------------------------
type X = Sum.Member<'A', TypeA> | Sum.Member<'B', TypeB>;
const X = Sum.create<X>();
const Codec1 = Sum.getCodec(X)({
A: TypeA,
B: TypeB,
});
// ------------------------
// Version 2
// ------------------------
type IntersectionToUnion<T> = T extends infer I
? { [K in keyof I]: I[K] }[keyof I]
: never;
const Codec2 = t.strict({
A: TypeA,
B: TypeB,
});
type T = t.TypeOf<typeof Codec2>;
type S<A> = {
[K in keyof A]: Sum.Member<K, A[K]>;
};
type S2 = IntersectionToUnion<S<T>>;
const S2 = Sum.create<S2>();
S2.mk.A({ a: 'a' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment