nicer unions
This commit is contained in:
parent
60d154c36b
commit
690bbfcfd8
@ -64,7 +64,8 @@ test("union", t => {
|
|||||||
.property("type", stringConstCodec("two"))
|
.property("type", stringConstCodec("two"))
|
||||||
.property("bar", stringCodec)
|
.property("bar", stringCodec)
|
||||||
.build("AltTwo");
|
.build("AltTwo");
|
||||||
const myUnionCodec: Codec<MyUnion> = unionCodec<MyUnion, "type">("type")
|
const myUnionCodec: Codec<MyUnion> = unionCodec<MyUnion>()
|
||||||
|
.discriminateOn("type")
|
||||||
.alternative("one", altOneCodec)
|
.alternative("one", altOneCodec)
|
||||||
.alternative("two", altTwoCodec)
|
.alternative("two", altTwoCodec)
|
||||||
.build<MyUnion>("MyUnion");
|
.build<MyUnion>("MyUnion");
|
||||||
|
@ -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.
|
* 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, {}>();
|
return new ObjectCodecBuilder<T, {}>();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function unionCodec<T, D extends keyof T>(
|
export function unionCodec<T>(): UnionCodecPreBuilder<T> {
|
||||||
discriminator: D,
|
return new UnionCodecPreBuilder<T>();
|
||||||
): UnionCodecBuilder<T, D, never> {
|
|
||||||
return new UnionCodecBuilder<T, D, never>(discriminator);
|
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user