Kit
Functions

getUnitCodec

getUnitCodec(): FixedSizeCodec<void, void, 0>

Returns a codec for void values.

This codec does nothing when encoding or decoding and has a fixed size of 0 bytes. Namely, it always returns undefined when decoding and produces an empty byte array when encoding.

This can be useful when working with structures that require a no-op codec, such as empty variants in getDiscriminatedUnionCodec.

Returns

FixedSizeCodec<void, void, 0>

A FixedSizeCodec<void, void, 0>, representing an empty codec.

Examples

Encoding and decoding a void value.

const codec = getUnitCodec();
 
codec.encode(undefined); // Produces an empty byte array.
codec.decode(new Uint8Array([])); // Returns `undefined`.

Using unit codecs as empty variants in a discriminated union.

type Message =
  | { __kind: 'Enter' }
  | { __kind: 'Leave' }
  | { __kind: 'Move'; x: number; y: number };
 
const messageCodec = getDiscriminatedUnionCodec([
  ['Enter', getUnitCodec()], // <- No-op codec for empty data
  ['Leave', getUnitCodec()], // <- No-op codec for empty data
  ['Move', getStructCodec([...])]
]);

Remarks

Separate getUnitEncoder and getUnitDecoder functions are available.

const bytes = getUnitEncoder().encode();
const value = getUnitDecoder().decode(bytes);

See

On this page