Get Started
Declare the values of a list’s filter with @k8ordo/field, name their type, and read a value that came from outside.
On this page
Install
npm install @k8ordo/fieldIt runs with:
- TypeScript 7 or later, when you write TypeScript
The guide for AI agents ships at node_modules/@k8ordo/field/docs/GUIDE.md. Point your AGENTS.md or the like at that path.
@k8ordo/field imports nothing, React included, so a declaration module loads on the server, in the browser and in vite.config.ts alike.
Declaring the values
src/lib/filter.tsimport { field } from '@k8ordo/field';
export const filter = {
q: field.string({ maxLength: 100 }),
page: field.integer({ min: 1, default: 1 }),
sort: field.enum(['new', 'price'], { default: 'new' }),
The values are literal types without `as const`
};field has one builder per kind. The builder names the kind, and its options the constraints and the default.
What a builder returns is a frozen object, which a package that takes the declaration reads.
The value type
import type { ValuesOf } from '@k8ordo/field';
import { filter } from './filter';
export type Filter = ValuesOf<typeof filter>;
// { q: string; page: number; sort: 'new' | 'price' }ValuesOf makes the type of the values a record of declarations reads. For one declaration, use ValueOf.
page and sort have a default, so neither includes undefined. q is text, which reads '' when there is no value.
Reading a value
import { field, read } from '@k8ordo/field';
import { filter } from './filter';
const { value, issues } = read(field.object(filter), {
q: 'shoes',
page: '0',
});
// value: { q: 'shoes', page: 1, sort: 'new' }
// issues: [{ path: ['page'], flag: 'rangeUnderflow', field: … }]read returns the value with every refused part replaced by its default, and the list of refusals. It never throws.
A refusal’s flag is named as HTML’s ValidityState names it. page of 0 is below min, so it is rangeUnderflow.
Where a declaration goes
Usually a declaration is handed to another package rather than read by hand.
- A URL or stored value:
@k8ordo/state - A form’s fields:
@k8ordo/form - A route’s parameters and environment variables:
@k8ordo/framework
Which declarations a package takes depends on the place. A state refuses a password, and a form a boolean that defaults to true. Either is a type error, and one that gets past the types throws as the definition is made, naming the field.