Created
February 7, 2024 22:38
-
-
Save Magellol/36b00fe158c414253d5ffa6726d873be to your computer and use it in GitHub Desktop.
Derive sum types from codecs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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