getUnionCodec
getUnionCodec<
TVariants
>(variants
,getIndexFromValue
,getIndexFromBytes
):Codec
<GetEncoderTypeFromVariants
<TVariants
>,GetDecoderTypeFromVariants
<TVariants
> &GetEncoderTypeFromVariants
<TVariants
>>
Returns a codec for encoding and decoding union types.
This codec serializes and deserializes union values by selecting the correct variant based on the provided index functions.
Unlike the getDiscriminatedUnionCodec, this codec does not assume a stored discriminator and must be used with an explicit mechanism for managing discriminators.
Type Parameters
Type Parameter | Description |
---|---|
TVariants extends readonly Codec <any >[] | An array of codecs, each corresponding to a union variant. |
Parameters
Parameter | Type | Description |
---|---|---|
variants | TVariants | The codecs for each variant of the union. |
getIndexFromValue | (value ) => number | A function that determines the variant index from the provided value. |
getIndexFromBytes | (bytes , offset ) => number | A function that determines the variant index from the byte array. |
Returns
Codec
<GetEncoderTypeFromVariants
<TVariants
>, GetDecoderTypeFromVariants
<TVariants
> & GetEncoderTypeFromVariants
<TVariants
>>
A Codec
for encoding and decoding union values.
Example
Encoding and decoding a union of numbers and booleans.
Remarks
If you need a codec that includes a stored discriminator, consider using getDiscriminatedUnionCodec.
Separate getUnionEncoder and getUnionDecoder functions are also available.