Kit
Functions

getUnionDecoder

getUnionDecoder<TVariants>(variants, getIndexFromBytes): Decoder<GetDecoderTypeFromVariants<TVariants>>

Returns a decoder for union types.

This decoder deserializes values by selecting the correct variant decoder based on the getIndexFromBytes function.

Unlike other codecs, this decoder does not assume a stored discriminator. It is the user's responsibility to manage discriminators separately.

For more details, see getUnionCodec.

Type Parameters

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

Parameters

ParameterTypeDescription
variantsTVariantsThe decoders for each variant of the union.
getIndexFromBytes(bytes, offset) => numberA function that determines the variant index from the byte array.

Returns

Decoder<GetDecoderTypeFromVariants<TVariants>>

A Decoder for decoding union values.

Example

Decoding a union of numbers and booleans.

const decoder = getUnionDecoder(
  [getU16Decoder(), getBooleanDecoder()],
  (bytes, offset) => (bytes.length - offset > 1 ? 0 : 1)
);
 
decoder.decode(new Uint8Array([0x2a, 0x00])); // 42
decoder.decode(new Uint8Array([0x01]));       // true
// Type is inferred as `number | boolean`

See

getUnionCodec

On this page