nicer unions

This commit is contained in:
Florian Dold 2019-12-14 18:00:03 +01:00
parent 60d154c36b
commit 690bbfcfd8
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
2 changed files with 10 additions and 5 deletions

View File

@ -64,7 +64,8 @@ test("union", t => {
.property("type", stringConstCodec("two"))
.property("bar", stringCodec)
.build("AltTwo");
const myUnionCodec: Codec<MyUnion> = unionCodec<MyUnion, "type">("type")
const myUnionCodec: Codec<MyUnion> = unionCodec<MyUnion>()
.discriminateOn("type")
.alternative("one", altOneCodec)
.alternative("two", altTwoCodec)
.build<MyUnion>("MyUnion");

View File

@ -233,6 +233,12 @@ export function mapCodec<T>(innerCodec: Codec<T>): Codec<{ [x: string]: T }> {
};
}
export class UnionCodecPreBuilder<T> {
discriminateOn<D extends keyof T>(discriminator: D): UnionCodecBuilder<T, D, never> {
return new UnionCodecBuilder<T, D, never>(discriminator);
}
}
/**
* Return a builder for a codec that decodes an object with properties.
*/
@ -240,8 +246,6 @@ export function objectCodec<T>(): ObjectCodecBuilder<T, {}> {
return new ObjectCodecBuilder<T, {}>();
}
export function unionCodec<T, D extends keyof T>(
discriminator: D,
): UnionCodecBuilder<T, D, never> {
return new UnionCodecBuilder<T, D, never>(discriminator);
export function unionCodec<T>(): UnionCodecPreBuilder<T> {
return new UnionCodecPreBuilder<T>();
}