Validation tags
Add built-in constraints and custom rules to field types.
A type tag is a type-only annotation that you intersect with a field type. A validation tag, such as MinLength<3> or TValidation<typeof notBlank>, adds a generated check. It does not change the TypeScript type that application code sees. TSerde is the type tag for the JSON form of a field.
import { model, type IModel } from '@exprtlabs/golem/model';
import type { MaxLength, MinLength } from '@exprtlabs/golem/tags';
import { validateInstance } from '@exprtlabs/golem/validation';
type TaggedTitle = string & MinLength<3> & MaxLength<80>;
export type TTaggedTask = IModel<{
title: TaggedTitle;
done: boolean;
}>;
export class TaggedTask extends model<TTaggedTask>() {}
export async function validateTaskTitles(): Promise<[boolean, boolean, boolean]> {
const short = new TaggedTask({ title: 'x', done: false });
const longEnough = new TaggedTask({ title: 'release', done: false });
const tooLong = new TaggedTask({ title: 'x'.repeat(81), done: false });
// -> [false, true, false]
return [
(await validateInstance(short)).length === 0,
(await validateInstance(longEnough)).length === 0,
(await validateInstance(tooLong)).length === 0,
];
}titlestays astringto application code. Tags do not coerce it.- Arguments must be literal types, such as
Minimum<0>orPattern<'^[A-Z]+$'>.
Add a built-in tag
Intersect the field type with each validation tag. TaggedTitle above is string & MinLength<3> & MaxLength<80>. Run npx golem generate after you save the model file.
Name a tag combination
Give a combination of tags a type alias and use the alias as the field type. A type parameter can supply a tag argument, so one alias serves every length.
import { model, type IModel } from '@exprtlabs/golem/model';
import type { MaxLength, Pattern } from '@exprtlabs/golem/tags';
import { validateInstance } from '@exprtlabs/golem/validation';
type Varchar<N extends number> = string & MaxLength<N>;
type Handle<N extends number> = Varchar<N> & Pattern<'^[a-z0-9_]+$'>;
export type TAccount = IModel<{
displayName: Varchar<80>;
handle: Handle<20>;
}>;
export class Account extends model<TAccount>() {}
export async function validateHandles(): Promise<[boolean, boolean]> {
const valid = new Account({ displayName: 'Ada', handle: 'ada_l' });
const tooLong = new Account({ displayName: 'Ada', handle: 'a'.repeat(21) });
// -> [true, false]
return [(await validateInstance(valid)).length === 0, (await validateInstance(tooLong)).length === 0];
}Handle<20>checksmaxLength: 20and the pattern. Aliases can use other aliases.- Inside an alias,
TSerdeandTValidationtaketypeofan exported function. - An alias or codec can come from an installed package. The generated file imports the codec through the
exportsof the package. When the package has noexportsfield, it imports by the path inside the package (RUNM1060).
Built-in validation constraints
Each family has its own tags. Every tag, its JSON Schema keyword and the field types it fits are in Built-in tags.
| Family | What it checks | Example |
|---|---|---|
| Numbers | Range, whole numbers and multiples | Minimum<N> |
| Strings | Length, pattern and format | MaxLength<N> |
| Arrays | Item count, uniqueness and matching items | UniqueItems |
| Objects | Property count, names and extra keys | MinProperties<N> |
| Related fields | Fields that depend on each other | DependentRequired<Map> |
| Alternatives | Branches of a schema | OneOf<Tuple> |
Object and array validation constraints
Schema-valued tags describe another TypeScript contract:
import { model, type IModel } from '@exprtlabs/golem/model';
import type {
Contains,
Format,
MinContains,
DependentRequired,
} from '@exprtlabs/golem/tags';
import { validateInstance } from '@exprtlabs/golem/validation';
type WatcherEmail = string & Format<'email'>;
type Watchers = string[] & Contains<WatcherEmail> & MinContains<1>;
type DueDates = {
dueOn?: string;
remindOn?: string;
} & DependentRequired<{ remindOn: ['dueOn'] }>;
export type TSubscription = IModel<{
watchers: Watchers;
dates: DueDates;
}>;
export class Subscription extends model<TSubscription>() {}
export async function checkSubscription(): Promise<[boolean, boolean]> {
const accepted = {
watchers: ['mina@example.com'],
dates: { dueOn: '2025-01-02', remindOn: '2025-01-01' },
};
const rejected = {
watchers: ['mina@example.com'],
dates: { remindOn: '2025-01-01' },
};
// -> [true, false]: the rejected dates have remindOn but no dueOn
return [
(await validateInstance(new Subscription(accepted))).length === 0,
(await validateInstance(new Subscription(rejected))).length === 0,
];
}Contains<T>counts matching elements.MinContainsandMaxContainsbound the count.DependentRequired<{ remindOn: ['dueOn'] }>requiresdueOnwheneverremindOnis present, so the rejected subscription above fails. In general it requires the listed keys when its trigger key is present.DependentSchemaschecks the whole object in that situation.PropertyNames,PatternPropertiesandUnevaluatedPropertiescheck keys or values without adding TypeScript index signatures.AdditionalProperties<V>makes each other key of the object a value of typeV.parse,stringifyandtoWireFormatconvert and write those keys byV, as they do for an index signature.AdditionalProperties<unknown>keeps the values as they are.AdditionalProperties<never>allows no other key.OneOf<[A, B]>,Not<T>andIfThenElsechoose or reject schema branches. None changes assignability or selects a converter.
Name the tag of a union
Discriminator<Key> names the property that tells the variants of a model union apart. Write it on a union of two or more objects. Golem reads that key and no other. Unions shows the placements.
import type { IModel } from '@exprtlabs/golem/model';
import type { Discriminator } from '@exprtlabs/golem/tags';
export type TEmail = IModel<{ kind: 'email'; address: string }>;
export type TPhone = IModel<{ kind: 'phone'; number: string }>;
// How to reach a task's assignee: by email or by phone. `kind` is the tag key.
export type TContact = IModel<{ value: (TEmail | TPhone) & Discriminator<'kind'> }>;| Parameter | Meaning |
|---|---|
Key | The property that each variant declares as a required literal. |
Default (optional) | The one variant that may lack Key. |
- Each variant declares
Keyas a required literal type, or a union of literals. No two variants share a value. A variant that breaks this rule stops generation (RUNM1087). - A union of two or more objects without the tag stops generation (RUNM1080).
- A tag on a value that is not such a union stops generation (RUNM1051).
- The tag does not change the TypeScript type. The generated model files carry no tag.
Add a default variant
Give Discriminator a second type argument to name the default variant. The default is the variant that has no tag, such as an SDK type from an OpenAPI document.
export type TNote = IModel<{ text: string }>;
// A note has no `kind`, so it is the default. A value whose `kind` matches no other variant is a note.
export type TContactOrNote = IModel<{ value: (TEmail | TPhone | TNote) & Discriminator<'kind', TNote> }>;- An object whose
kindis missing, or matches no other variant, becomes the default. - The default must be a variant of the union, and it must not declare
Keyitself. Otherwise generation stops (RUNM1051). - Only the default may lack
Key.
Document a tagged union
A docs job writes a tagged union as oneOf with discriminator.propertyName set to Key, and a mapping from each value to its schema.
- OpenAPI 3.2 states a default variant as
defaultMapping. - OpenAPI 3.1 has no
defaultMapping, so the docs job writes a union with a default asanyOfwith nodiscriminator. Agolem-openapi-tsjob that reads that 3.1 document stops withOPENAPI_UNION_DISCRIMINATOR_MISSINGwhen the variants are models. For a union with a default, use OpenAPI 3.2. It is the defaultopenapiVersion. - A
golem-openapi-tsjob rejects an OpenAPI 3.1 document that writesdefaultMapping: it is a keyword of 3.2. - An SDK that
golem-openapi-tsgenerates follows thediscriminatorof its document. On OpenAPI 3.2 it followsdefaultMappingtoo.
Formats
On a model field, Format<'name'> applies to a string, or to a number for a number format such as number & Format<'int32'>. A number format also applies to schemas from an OpenAPI document, where a number schema has format: int32. A format on the wrong type, such as email on a number or int32 on a string, stops generation (RUNM1051). Golem checks these names:
| Value | Format names | Applies to |
|---|---|---|
| Strings | date-time, date, time, duration, email, hostname, ipv4, ipv6, uri, uri-reference, uuid, regex, byte, json-pointer, relative-json-pointer | Model fields and OpenAPI schemas |
| Numbers | int32, int64, float, double | Model fields and OpenAPI schemas |
| Any string | password, binary, media-range | Model fields and OpenAPI schemas |
A format name that golem does not check stops generation. Set unknownFormats: warn in golem.yaml to report it and continue.
Add a custom field rule
Use TValidation<typeof predicate> when a built-in tag cannot express the validation constraint. Declare the predicate in its own module and import it into the model file. A predicate declared in a model file is a generation error (RUNM1065).
import type { MinLength, TValidation } from '@exprtlabs/golem/tags';
export function notBlank(value: string): boolean | string {
return value.trim().length > 0 || 'Enter a title.';
}
export type TaskTitle = string & MinLength<1> & TValidation<typeof notBlank>;import { model, type IModel } from '@exprtlabs/golem/model';
import type { TaskTitle } from './task-input-rule.js';
export type TTaskInput = IModel<{
title: TaskTitle;
done: boolean;
}>;
export class TaskInput extends model<TTaskInput>() {}- Export a synchronous function with one required value.
- Return
trueto accept,falsefor a default message, or a string for a custom message. - Built-in constraints run first. Do not depend on the order of several predicates on one value.
- Generated checks run before the predicate. A predicate on the model field type checks the model value. A predicate on the parameter type of a
TSerdedecoder checks the JSON value. - A field can add a rule to an SDK type, such as
Money & TValidation<typeof extra>. The rule runs with the checks of the SDK type. - For rules that depend on another field or an asynchronous lookup, use an instance validator rule.
The generated file imports your predicate. OpenAPI documents carry only the JSON schema, never the predicate.
