Kit
Functions

getUnionEncoder

getUnionEncoder<TVariants>(variants, getIndexFromValue): Encoder<GetEncoderTypeFromVariants<TVariants>>

Returns an encoder for union types.

This encoder serializes values by selecting the correct variant encoder based on the getIndexFromValue function.

Unlike other codecs, this encoder does not store the variant index. It is the user's responsibility to manage discriminators separately.

For more details, see getUnionCodec.

Type Parameters

Type ParameterDescription
TVariants extends readonly Encoder<any>[]An array of encoders, each corresponding to a union variant.

Parameters

ParameterTypeDescription
variantsTVariantsThe encoders for each variant of the union.
getIndexFromValue(value) => numberA function that determines the variant index from the provided value.

Returns

Encoder<GetEncoderTypeFromVariants<TVariants>>

An Encoder for encoding union values.

Example

Encoding a union of numbers and booleans.

const encoder = getUnionEncoder(
  [getU16Encoder(), getBooleanEncoder()],
  value => (typeof value === 'number' ? 0 : 1)
);
 
encoder.encode(42);
// 0x2a00
//   └── Encoded number (42) as `u16`
 
encoder.encode(true);
// 0x01
//   └── Encoded boolean (`true`) as `u8`

See

getUnionCodec

On this page