Grounds
    Preparing search index...

    Function REnum

    • Creates an enum schema from tagged variant definitions.

      Enums represent sum types (tagged unions) with multiple possible variants. Encoding infers the variant automatically via schema matching; decoding returns the unwrapped value directly.

      Type Parameters

      Parameters

      • variants: T

        Object mapping variant names to variant() schemas

      Returns TREnum<T>

      TypeBox schema for enum type (union of all variants)

      Simple enum:

      import { REnum, variant, RNull, RString } from '@grounds/schema';
      import { createCodec, type Static } from '@grounds/schema';

      const StatusSchema = REnum({
      idle: variant(0, RNull()),
      loading: variant(1, RNull()),
      success: variant(2, RString()),
      error: variant(3, RString())
      });

      type Status = Static<typeof StatusSchema>;
      // "idle" | "loading" | { success: string } | { error: string }

      const codec = createCodec(StatusSchema);
      codec.encode({ success: 'Data loaded' });
      codec.encode({ error: 'Network failed' });

      Discriminated enum with structs:

      import { REnum, RStruct, variant, field, RString, RU32 } from '@grounds/schema';

      const MessageSchema = REnum({
      text: variant(0, RStruct({
      content: field(0, RString())
      })),
      reaction: variant(1, RStruct({
      emoji: field(0, RString())
      }))
      });

      type Message = Static<typeof MessageSchema>;
      // { text: { content: string } } | { reaction: { emoji: string } }

      Encoding: Variant is inferred automatically by checking each variant schema against the input value using TypeBox's Value.Check. The first matching variant is encoded. Encoding fails if value matches zero or multiple variants.

      Decoding: Returns the unwrapped value directly (not { variant, value }). Users handle variant discrimination via discriminator fields they define in struct variants or via TypeScript type guards.

      This API differs from typical enum implementations by removing the variant wrapper, simplifying consumption. See ADR 0002 for full rationale.