Delta-Pack - v0.2.9
    Preparing search index...

    Function UnionType

    • Create a discriminated union type from multiple named types or classes.

      Unions allow a value to be one of several different types. Each variant is distinguished by a _type discriminator field. The variant index is encoded using the minimum bits needed.

      Works in both schema mode (with ObjectTypes) and decorator mode (with classes).

      Type Parameters

      • const N extends string
      • const V extends readonly NamedType[]

      Parameters

      • name: N

        The union type name (must start with uppercase, e.g., "Message")

      • options: V

        Array of named types (schema mode) or class constructors (decorator mode)

      Returns { type: "union"; options: V; name: N; numBits: number }

      // Schema mode - union of object types
      const TextMessage = ObjectType("TextMessage", {
      content: StringType(),
      });

      const ImageMessage = ObjectType("ImageMessage", {
      url: StringType(),
      width: IntType(),
      height: IntType(),
      });

      const Message = UnionType("Message", [TextMessage, ImageMessage]);

      const api = load(Message);
      const msg = { _type: "TextMessage", content: "Hello!" };
      // Decorator mode - union of classes
      class Cat { meow = StringType(); }
      class Dog { bark = StringType(); }

      const Animal = UnionType("Animal", [Cat, Dog]);
    • Create a discriminated union type from multiple named types or classes.

      Unions allow a value to be one of several different types. Each variant is distinguished by a _type discriminator field. The variant index is encoded using the minimum bits needed.

      Works in both schema mode (with ObjectTypes) and decorator mode (with classes).

      Type Parameters

      • const N extends string
      • const V extends readonly (new (...args: any[]) => any)[]

      Parameters

      • name: N

        The union type name (must start with uppercase, e.g., "Message")

      • classes: V

      Returns ClassUnionDef<N, V>

      // Schema mode - union of object types
      const TextMessage = ObjectType("TextMessage", {
      content: StringType(),
      });

      const ImageMessage = ObjectType("ImageMessage", {
      url: StringType(),
      width: IntType(),
      height: IntType(),
      });

      const Message = UnionType("Message", [TextMessage, ImageMessage]);

      const api = load(Message);
      const msg = { _type: "TextMessage", content: "Hello!" };
      // Decorator mode - union of classes
      class Cat { meow = StringType(); }
      class Dog { bark = StringType(); }

      const Animal = UnionType("Animal", [Cat, Dog]);