Kit
Functions

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 ParameterDescription
TVariants extends readonly Codec<any>[]An array of codecs, each corresponding to a union variant.

Parameters

ParameterTypeDescription
variantsTVariantsThe codecs for each variant of the union.
getIndexFromValue(value) => numberA function that determines the variant index from the provided value.
getIndexFromBytes(bytes, offset) => numberA 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.

const codec = getUnionCodec(
  [getU16Codec(), getBooleanCodec()],
  value => (typeof value === 'number' ? 0 : 1),
  (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)
);
 
const bytes1 = codec.encode(42); // 0x2a00
const value1: number | boolean = codec.decode(bytes1); // 42
 
const bytes2 = codec.encode(true); // 0x01
const value2: number | boolean = codec.decode(bytes2); // true

Remarks

If you need a codec that includes a stored discriminator, consider using getDiscriminatedUnionCodec.

Separate getUnionEncoder and getUnionDecoder functions are also available.

const bytes = getUnionEncoder(variantEncoders, getIndexFromValue).encode(42);
const value = getUnionDecoder(variantDecoders, getIndexFromBytes).decode(bytes);

See

On this page