Skip to main content
On this page

Typing

Encodexx provides several helper types to simplify your work. They assist in extracting and transforming the types of schemas and serialized objects. This can be useful both when creating custom types and during regular use of the serializer.

  • ExtractObj - Helps extract the object type that a schema serializes.

    import { Serializer, t, ExtractObj } from "encodexx"
    const serializer = new Serializer({
    name: t.or(t.int8, t.string, t.date),
    role: t.enumerate("user", "admin", "guest"),
    })
    type TSchemaType = ExtractObj<typeof serializer>
    // TSchemaType is { name: number | string | Date, role: "user" | "admin" | "guest" }
    const obj: TSchemaType = {
    name: 12,
    role: "admin"
    }
    serializer.encode(obj)
  • ArraySingle - When creating schemas in separate variables, you might encounter an error related to an indeterminate number of elements in schemas. To resolve this, you can use the ArraySingle type.

    import { ArraySingle, t, Serializer } from "encodexx"
    const schema = { arr: [t.int8] }
    new Serializer(schema as ArraySingle<typeof schema>)
  • TYPE_SYMBOL - A symbol present in all types within the t object or created via customType().

    import { t, TSchema, TYPE_SYMBOL } from "encodexx";
    export function orNone<T extends TSchema>(type: T) {
    if (TYPE_SYMBOL in type) return t.or(t.none, type);
    return t.or(t.none, t.schema(type));
    }
  • TSchema - The type representing a schema. It can consist of a single type or be a complex structure.

  • TConvertValueToType - Helps convert a schema type into the type of the object that the schema processes.

    import { t, TConvertValueToType } from "encodexx";
    const schema = {
    name: t.str,
    enums: t.enumerate("A", "B", "C"),
    };
    type TValue = TConvertValueToType<typeof schema>;
    // TValue is { name: string, enums: "A" | "B" | "C" }