CCC Docs
    Preparing search index...

    Function union

    • Constructs a union codec that can serialize and deserialize values tagged with a type identifier.

      In accordance with the Molecule specification, union is always a dynamic-size type, regardless of whether its variants have identical fixed lengths.

      If you need a fixed-size union type compatible with fixed containers like struct, array, or vector (as FixVec), use fixedUnion instead.

      Serialization format:

      1. 4-byte little-endian unsigned integer for the variant ItemId (tag).
      2. Encoded bytes of the selected variant.

      Type Parameters

      • T extends Record<string, CodecLike<any, 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, number | null | undefined>

        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>
          | { inner: UnionEncodable<T> },
          UnionDecoded<T, keyof T>,
          ChildContext<T>,
      >

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

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

      // Fixed-size union (explicit extension):
      fixedUnion({ cafe: Uint16, bee: Uint16 });