Skip to main content

The schema() Function

Caution

When using t.or() together with large t.schema() objects without a discriminateBy field, performance issues may arise. Use with caution.

Overview

t.schema(schema, discriminateBy?): TCustomType
  • t.schema() is used to pass complex structures to t.or.
  • t.schema() is also helpful when developing custom types.

Example Usage

import { Serializer, t } from "encodexx"
const serializer = new Serializer({
ages: [t.or(t.schema([t.uint8]), t.str)],
message: t.or(t.str, t.none)
})
serializer.encode({
ages: [[12], "493", "not a number", [124, 200]],
message: null
});

Comparing Schemas

When deciding which schema to apply, t.or() automatically determines the relevant type by sequentially matching the object against each schema. With multiple complex schemas, these repeated checks can negatively impact performance. It’s recommended to specify the discriminateBy argument to perform comparisons based on a specific field.

import { Serializer, t } from "encodexx"
const serializer = new Serializer({
users: [
t.or(
t.schema({ name: t.str, type: t.enumerate("USER") }, "type"),
t.schema({ content: t.str, age: t.uint8, type: t.enumerate("ADMIN") }, "type")
),
],
});
serializer.encode({
users: [
{ name: "ad", type: "USER" },
{ content: "content", age: 15, type: "ADMIN" },
{ name: "another", type: "USER" },
]
});