CCC Docs
    Preparing search index...
    • Constructs a union codec that can serialize and deserialize values tagged with a type identifier.

      If all variants have the same fixed size, the resulting union codec is fixed-size (header + payload). Otherwise, it falls back to a dynamic-size codec.

      Serialization format:

      1. 4-byte little-endian unsigned integer for the variant index.
      2. Encoded bytes of the selected variant.

      Type Parameters

      • T extends Record<string, CodecLike<any, any>>

        A record mapping variant names to codecs.

      Parameters

      • codecLayout: T

        An object whose keys are variant names and values are codecs for each variant.

      • Optionalfields: Record<keyof T, undefined | null | number>

        Optional mapping from variant names to custom numeric IDs. If omitted, the index of each variant in codecLayout is used as its ID.

      Returns Codec<UnionEncodable<T, keyof T>, UnionDecoded<T, keyof T>>

      // Dynamic union without custom numeric IDs
      union({ cafe: Uint8, bee: Uint16 })

      // Dynamic union with custom numeric IDs
      union({ cafe: Uint8, bee: Uint16 }, { cafe: 0xcafe, bee: 0xbee })

      // Fixed-size union without custom numeric IDs
      const PaddedUint8 = struct({ data : u8, padding : u8 })
      union({ cafe: PaddedUint8, bee: Uint16 });

      // Fixed-size union with custom numeric IDs
      union({ cafe: PaddedUint8, bee: Uint16 }, { cafe: 0xcafe, bee: 0xbee })