Field types
Pick the TypeScript shape of a field and see how golem constructs, converts and validates it.
Scalars, arrays and objects
| TypeScript shape | Runtime and JSON |
|---|---|
string, number, boolean, null, undefined | stored as is |
bigint | needs a TSerde codec |
| string, number and boolean literals | kept and checked |
| arrays and tuples | items convert recursively; tuple length and optional or rest positions are checked |
| object types | known properties convert; extra properties fail validation unless exact is false |
| intersections | the fields merge |
| unions | supported unions |
a declaration alias, such as TPlace | a nested plain object, still converted |
your class, such as Place | a nested instance of that class |
Date | an ISO date-time string in JSON, restored with Date parsing |
Temporal.Instant, Temporal.PlainDate and the other Temporal classes, or the @exprtlabs/golem/temporal types TemporalInstant, TemporalPlainDate and so on | an ISO 8601 string in JSON (Dates and times) |
| a recursive type alias | converted and validated at every level |
any, unknown | accepted only when allowAny is true |
An undefined property is left out of JSON. bigint needs a codec that writes it as JSON, such as a string. Without one, stringify rejects it.
Validation tags add checks to these shapes, such as MinLength on a string. A Date is always checked as an ISO date-time string in JSON. On a model field, Format applies to a string (Formats), so use TValidation for your own rule on a Date.
Dates and times
Hold dates in models and the SDK as Date or as Temporal values, and send them as ISO 8601 strings.
Date and the Temporal classes are built-in TSerde types. Golem gives each class a default pair of functions, as a TSerde tag does. A field typed Date or Temporal.Instant needs no tag, and a TSerde tag on the same type replaces the default.
import { model, type IModel } from '@exprtlabs/golem/model';
export type TReminder = IModel<{
title: string;
remindAt: Date;
}>;
export class Reminder extends model<TReminder>() {}Use Date fields
A Date field is an ISO date-time string in JSON. parse and fromWireFormat restore it as a Date, and stringify and toWireFormat write it back.
import { parse } from '@exprtlabs/golem/serde';
import { Reminder } from './reminder.model.js';
export function readReminder(text: string): Reminder {
return parse<Reminder>(text); // -> a Reminder whose remindAt is a Date
}Golem writes a Date in UTC with milliseconds. A reader that gets "2026-01-02T10:00:00Z" holds a Date and writes back "2026-01-02T10:00:00.000Z". A string with an offset, such as +02:00, is converted to UTC and written with Z. The Date keeps the moment, not the original text.
- To keep the exact text, declare the field as
string & Format<'date-time'>. The value stays a string, and golem checks that it is a date-time (Formats). - To write another form, declare it as
Date & TSerde<typeof encode, typeof decode>. Yourencodefunction writes the text anddecodereads it (change the JSON form). The text comes from theDate, so it fits a fixed form, such as seconds with no milliseconds.
Use Temporal fields
Declare a field with a type from @exprtlabs/golem/temporal. Each type holds its Temporal class in the model and an ISO 8601 string in JSON.
You can also write the class itself: Temporal.Instant, Temporal.ZonedDateTime, Temporal.PlainDate, Temporal.PlainDateTime, Temporal.PlainTime or Temporal.Duration. It converts to the same JSON string as the matching type.
import { model, type IModel } from '@exprtlabs/golem/model';
import type { TemporalDuration, TemporalInstant, TemporalPlainDate } from '@exprtlabs/golem/temporal';
export type TSchedule = IModel<{
startsAt: TemporalInstant;
day: TemporalPlainDate;
length: TemporalDuration;
}>;
export class Schedule extends model<TSchedule>() {
public get endsAt(): Temporal.Instant {
return this.startsAt.add(this.length);
}
}- Add
"esnext.temporal"tocompilerOptions.libintsconfig.json. - Load a
Temporalbefore converting. Installtemporal-polyfilland importtemporal-polyfill/globalonce, before the first conversion. Without aTemporal, conversion fails with "Temporal is not available".
import 'temporal-polyfill/global';
import { parse, stringify } from '@exprtlabs/golem/serde';
import { Schedule, type TSchedule } from './schedule.model.js';
export function readSchedule(text: string): Schedule {
return parse<Schedule>(text); // -> a Schedule: startsAt is a Temporal.Instant, endsAt is 2025-01-02T04:34:05Z
}
export function writeSchedule(schedule: Schedule): string {
// -> '{"startsAt":"2025-01-02T03:04:05Z","day":"2025-01-02","length":"PT1H30M"}'
return stringify<TSchedule>(schedule);
}| Field type | Model value | JSON |
|---|---|---|
TemporalInstant | Temporal.Instant | 2025-01-02T03:04:05Z |
TemporalPlainDate | Temporal.PlainDate | 2025-01-02 |
TemporalDuration | Temporal.Duration | PT1H30M |
A Temporal value is written in its own toString() form. A TemporalInstant shows fractional seconds only when it has them, for example 2025-01-02T03:04:05.250Z.
TemporalZonedDateTime, TemporalPlainDateTime and TemporalPlainTime work the same way.
Check a Date or Temporal field
Validation checks the model value of a Date or Temporal field with instanceof.
- A value of another type fails with one
instanceissue at the field path. For aDate, the message isExpected an instance of Date. - An invalid
Date, such asnew Date(NaN), fails in the same way. - Decoding reads a string only. Another JSON value throws
Deserializationat every validation level, off included. - The JSON value is checked as a
date-timestring for aDate, or as the form of the class for a Temporal field.
Use Temporal values in a client
Set dates: temporal on the SDK job. The generated client then maps format: date-time to Temporal.Instant, format: date to Temporal.PlainDate and format: duration to Temporal.Duration. Without the key, the same fields are Date values.
With dates: temporal, format: duration means the Temporal form in every position of the document. It accepts the text that Temporal.Duration writes, such as PT0.5S, PT1H30S and P1Y2D. Without dates: temporal, a duration string must follow the RFC 3339 format, which has no fractional seconds.
- input: provider/provider.yaml
output: provider/sdk
name: Provider
dates: temporalThe client converts the JSON strings for you, so the response body holds the Temporal values:
export async function readSettlementDate(client: ProviderClient, id: string): Promise<Temporal.PlainDate | undefined> {
const response = await client.getCharge().execute({ path: { id } });
if (response.status !== 200) return undefined;
return response.body.settlesOn; // settlesOn is `format: date`, so the client returns a Temporal.PlainDate
}A model of your own over the SDK type writes the strings back with toWireFormat:
export function describeCharge() {
const record = fromWireFormat<ChargeRecord>({
charge: {
id: 'charge-1',
status: 'pending',
money: { amount: '25.00', currency: 'USD' },
createdAt: '2025-01-02T03:04:05Z',
settlesOn: '2025-02-01',
},
});
record.charge.settlesOn = Temporal.PlainDate.from('2025-02-03');
return toWireFormat<TChargeRecord>(record).charge;
// { ..., createdAt: '2025-01-02T03:04:05Z', settlesOn: '2025-02-03' }
}format: time stays a string. A Temporal.Instant is written with Z, so an offset in the original string is not kept. The generated client needs the same esnext.temporal setting, or skipLibCheck: true, and a loaded Temporal.
Objects and exact
The second type argument of IModel and IObject sets two options for that declaration. exact controls extra properties. allowAny controls any and unknown.
import type { IModel } from '@exprtlabs/golem/model';
export type TOpenLabel = IModel<{ name: string }, { exact: false }>;
export type TExactLabel = IModel<{ name: string }>;
export type TIntegrationEvent = IModel<{ payload: any }, { allowAny: true }>;The options exact and allowAny
| Option | Default | Where you set it | Effect |
|---|---|---|---|
exact | true | The root of golem.yaml for every model, or the options of one IObject or IModel | true: an extra property fails validation, also in a nested plain object. false: a key that the model does not list is admitted. |
allowAny | false | The root of golem.yaml for every model, or the options of one IObject or IModel | false: a field typed any or unknown fails with RUNM1011. true: the field is allowed (any and unknown). |
- The option on the declaration overrides
golem.yaml, andgolem.yamloverrides the default.{ allowAny: false }tightens a permissivegolem.yaml. - A docs job reads the types that a controller signature spells out, such as an inline body, with
exact: false, whatevergolem.yamlsays. A model that a signature names keeps its ownexact(derived type names). - A key on an instance that its model does not declare is program state, not an extra property. Codecs never report it as an unknown key and never write it to JSON, also inside an
unknownoranyfield. - Input from JSON or a request stays exact. Constructors assign declared fields only.
- To decode input that holds more keys than the model declares, such as
process.envor the headers of a request, pass{ strip: true }toparseorfromWireFormat.stringifyandtoWireFormattake it too, for a value with an extra key, such as a database row. A closed object then loses each key that it does not declare, at every level, and the check passes. A map, anAdditionalPropertiestag,PatternPropertiesand an object withexact: falsekeep their extra keys. A union of objects that has aDiscriminatortag picks the variant by the tag first (strip).
Nested models and derived types
A field typed with your class, such as office: Place, holds an instance of that class. A field typed with the declaration alias (TPlace) holds a plain object. Pick, Omit, Partial, Required and Readonly produce a derived type as a plain object.
import { model, type IModel } from '@exprtlabs/golem/model';
import { fromWireFormat } from '@exprtlabs/golem/serde';
export type TPlace = IModel<{
id: string;
city: string;
country: string;
}>;
export class Place extends model<TPlace>() {}
export type TAssignee = IModel<{
office: Place;
site: Omit<TPlace, 'id'>;
draft: Partial<Pick<TPlace, 'city' | 'country'>>;
}>;
export class Assignee extends model<TAssignee>() {}
export function loadAssignee(): Assignee {
// -> an Assignee: office is a Place, and site is a plain object
return fromWireFormat<Assignee>({
office: { id: 'place-1', city: 'Hanoi', country: 'VN' },
site: { city: 'Da Nang', country: 'VN' },
draft: { city: 'Hue' },
});
}A derived type keeps field conversion and validation.
A derived type is exact by default, like any model. Put a whole-object TValidation predicate or TSerde formatter on the derived type itself. Do not reuse one that you wrote for another shape.
Unions
Golem converts the unions below.
Supported without a tag:
- scalar types only, such as
string | number, and literal unions, such as'paid' | 'pending' - optional and nullish values:
T | undefined,T | null - one object, model or class beside scalars:
string | TPlace - strings, numbers, booleans or literals beside one array or one tuple, as in query objects (
status?: Status | Status[]). The items can convert:string | Date[]. A Date can be the only scalar beside the array:Date | Date[],Date | string[] - a model beside an array of that model:
TPlace | TPlace[] - strings, numbers, booleans or literals beside one array and one object or model:
string | string[] | TPlace. TheJsonValuealias under Recursive type aliases has this shape
A union of two or more objects needs a declared tag, as the next section shows.
Declare the tag of an object union
An object union names its tag key in the type with Discriminator. Golem reads that key and no other. The variants can be object types, models, IObject types, SDK models or records.
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'> }>;- Put
Discriminator<'kind'>on the union. Import it from@exprtlabs/golem/tags. - Declare
kindin each variant as a required literal type, or as a union of literals. - Give each variant values of its own. Two variants cannot share a value.
- The tag does not change the TypeScript type. Your code sees the same union.
- A union without the tag stops generation with
RUNM1080. A variant without the key, or a shared value, stops it withRUNM1087.
The tag works at every position: a field, an optional field, an array item, a record value and a tuple item. Write it on the union itself or on an alias of the union. Write null outside the tag, and put an array of tagged unions in parentheses:
// An alias names the tagged union once.
export type TContactValue = (TEmail | TPhone) & Discriminator<'kind'>;
export type TContactBook = IModel<{
primary: TContactValue;
// `null` stays outside the tag.
backup: TContactValue | null;
others: TContactValue[];
}>;- TypeScript reduces
null & Discriminator<'kind'>tonever.(TEmail | TPhone | null) & Discriminator<'kind'>therefore losesnull. othersabove is an array of the tagged union: the parentheses wrap the union and its tag, and the brackets follow.
Scalars, literals, one Date, one array or tuple, and null can sit beside the tagged objects, as in (string | TEmail | TPhone) & Discriminator<'kind'>. So can a TSerde class value whose JSON form is a scalar, such as a URL written as a string. Golem picks a variant in this order:
- The JSON type of the value picks a scalar, an array or
null. - For an object, the value of
kindpicks the variant. - An object whose
kindis missing or matches no variant is an error, unless the tag names a default variant.
Recursive type aliases
A type alias can refer to itself, in any shape: a union, an array, a tuple or a record. Golem generates one function for the alias, so a recursive alias needs no model around it. For example, type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue } is a valid field type, as in IModel<{ payload: JsonValue }>.
Use the alias as a field type, as an optional field or as an array item. Golem validates and converts every level. stringify and toWireFormat throw an error for a value that contains itself.
A type alias that does not refer to itself stays part of the field type. A recursive alias that holds a Date or a model converts the Date or the model at every level. A cycle that golem cannot name stops generation with RUNM1056.
any and unknown
A field typed any or unknown fails unless allowAny is true (the options table). The TIntegrationEvent declaration above sets it for one model.
allowAny: trueskips inferred structure and conversion for that field.- Explicit tags still run, and the JSON value must still be representable as JSON.
- Neither
allowAnynorexactchanges which fieldstoWireFormatemits. - A referenced model keeps its own policy.
Full examples: examples/models and examples/payments.
