Introduction
The Valof Book is both a guide and a reference. Read it in order to learn the conventions, or use the sidebar to find a specific topic.
Important
Valof is pre-1.0. A minor release can change the API. Read the release notes before upgrading.
Why Valof?
Valof is a TypeScript library for branded, immutable domain types, such as value objects and enums. It enforces the conventions through types and linting.
-
Nominal-ish typing with a phantom brand: TypeScript distinguishes one Val type from another, with nothing to pay at runtime.
-
Values as plain data: Vals stay objects, arrays and primitives. They serialize without adapters and fit directly into React and other framework state. No classes, no prototypes.
-
Immutability: Vals are immutable. Their types are deeply readonly, and
sealcopies its input, so an original reference cannot mutate them. -
No
ascasts in your code: Valof owns the cast required to construct a branded value. -
Companion object: Keep a type’s constructor and functions together without a class. The first Val parameter is inferred.
-
“Parse, don’t validate”: Every creation and derivation goes through one
seal.1 Use any validation library and any Result type. -
Copy only what changes:
patchcopies only the paths it changes. Untouched branches keep their reference identity. -
Rust-like abstractions:
Enumis a closed set of variants with exhaustivematch.Traitshares behavior across Vals.dynadds dynamic dispatch without classes, holding different types together. -
Built-in linter: Catch convention violations through ESLint, Oxlint or the standalone command. Linting shows the setup.
-
Lightweight: Starts from 965 B gzipped, with no runtime dependencies.
For background on individual features, see TypeScript Problems Valof Addresses.
Examples
import { Enum, Trait, Val, type Dyn, type Self } from "valof";
type Result<T> = { ok: T } | { err: string };
type TaskId = Val<"TaskId", string>;
const TaskId = Val.companion<TaskId>().build();
type Status = Enum<"Status", { Todo: { due: string }; Done: { at: string } }>;
const Status = Enum.companion<Status>().build();
type Summarizable = Trait<"Summarizable", { title: string }, { summarize: (self: Self) => string }>;
const Summarizable = Trait.companion<Summarizable>().build();
type Task = Val<"Task", { id: TaskId; status: Status; tags: string[] }, Summarizable>;
const Task = Val.companion<Task>()
.implSeal((task, seal): Result<Task> =>
task.title.trim() === "" ? { err: "empty title" } : { ok: seal(task) },
)
.impl(({ patch }) => ({
complete: (task, at: string) => patch(task, { status: Status.Done.create({ at }) }),
}))
.implTrait(Summarizable, () => ({
summarize: (t): string =>
Status.match(t.status, {
Todo: (s) => `${t.title} (due ${s.due})`,
Done: () => `${t.title} (done)`,
}),
}))
.build();
type Note = Val<"Note", { text: string }, Summarizable>;
const Note = Val.companion<Note>()
.implTrait(Summarizable, () => ({ summarize: (n) => n.title }))
.build();
function main() {
const result = Task.seal({
id: TaskId.seal("t1"),
title: "Write the README",
status: Status.Todo.create({ due: "10-31" }),
tags: ["docs"],
});
if ("err" in result) throw result.err;
const task = result.ok;
task.status._tag; // "Todo"
const done = Task.complete(task, "10-27");
if ("err" in done) throw done.err;
done.ok.status._tag; // "Done"
done.ok.tags === task.tags; // true: structural sharing
// Dynamic dispatch, as in Rust's `Box<dyn Trait>`. Each item calls its own type's `summarize`.
const board: Dyn<Summarizable>[] = [
Summarizable.dyn(Task, task),
Summarizable.dyn(Note, Note.seal({ title: "Ideas", text: "..." })),
];
board.map((item) => item.summarize()).forEach((s) => console.log(s)); // "Write the README (due 10-31)", "Ideas"
}
function errors(task: Task) {
Task.seal({ ...task, title: " " }); // { err: "empty title" }
// @ts-expect-error a plain string has no TaskId brand
Task.seal({ ...task, id: "t2" });
// @ts-expect-error Vals are deeply readonly
task.tags.push("urgent");
}
-
Two paths skip a companion’s seal:
Val.ofand.implCreate.noseal. ↩
TypeScript Problems Valof Addresses
This chapter explains the TypeScript problems behind individual Valof features. Use the sidebar for how to use the library.
Branding
Two values can have the same representation but different meanings:
type UserId = string;
type OrderId = string;
declare const userId: UserId;
let orderId: OrderId;
orderId = userId; // allowed: both types are string
A brand lets TypeScript distinguish them without changing their runtime representation. A
branded type normally needs a constructor that contains a type assertion. This keeps assertions out
of callers, but every branded type still needs the same constructor boilerplate, including an as
cast. A companion’s seal is that constructor. Declare the type and its companion together.
Val covers names, construction and the rules that keep the brand
intact:
type UserId = Val<"UserId", string>;
const UserId = Val.companion<UserId>().build();
const id = UserId.seal("u1");
Immutability
Readonly<T> is shallow. TypeScript has no built-in DeepReadonly, and a mutable original
reference can still change a readonly view. A recursive DeepReadonly type protects nested fields,
but updating one immutably still means rebuilding each object on the path.
Valof makes these conventions the default. Val applies DeepReadonly, its constructor copies the
input to remove mutable aliases, patch rebuilds only the paths it changes, and .nocopy is the
explicit escape hatch for a payload that already has no mutable aliases.
Immutability shows the copy and .nocopy contracts:
type Profile = Val<"Profile", { name: string; address: { city: string } }>;
const Profile = Val.companion<Profile>().build();
const profile = Profile.seal({ name: "alice", address: { city: "Osaka" } });
const changed = Profile.patch(profile, { address: { city: "Tokyo" } });
Companion objects
A TypeScript type does not create a value namespace. Its functions are usually standalone:
type User = { id: string; name: string; nickname?: string };
function getUserDisplayName(user: User) {
return user.nickname ?? user.name;
}
function formatUserLabel(user: User, separator: string) {
return user.id + separator + getUserDisplayName(user);
}
The type name appears in each function name to keep related functions recognizable. Each function also repeats the type annotation for its first parameter.
A class provides a namespace for its functions, but also turns each value into a class instance.
Keeping its instances immutable requires readonly on every field and nested property. Its JSON
shape depends on property enumerability unless you write and maintain a toJSON mapping.
A companion object collects the constructor and functions under the type’s
name while values remain plain data. Val.companion<V>().impl(() => ({ ... })).build() creates it.
The result exposes seal and the registered members:
type User = Val<"User", { name: string }>;
const User = Val.companion<User>()
.impl(() => ({ greeting: (user) => `Hi, ${user.name}` }))
.build();
User.greeting(User.seal({ name: "alice" }));
Parse, don’t validate
Valof makes parsing a convention, in two steps. An .implAssoc member decodes a wire format into
the payload, and the seal turns the payload into a Val. A companion has one seal, and create,
patch and the .implAssoc members pass their payloads to it.1 A custom seal returns a
validated, normalized Val or its failure, so the result type records that parsing succeeded.
Start with Val.companion<V>() and register the checks with .implSeal. The resulting .seal
returns the value or the seal’s failure.
Custom Constructors and Invariants explains schemas, normalization,
generated fields and .implAssoc:
type Age = Val<"Age", number>;
const Age = Val.companion<Age>()
.implSeal((value, seal) => (value >= 0 ? seal(value) : new Error("age must not be negative")))
.build();
const age = Age.seal(30); // Age | Error
Enums
An enum keeps a closed set of variants in one declaration and requires a handler for
every variant, or _ for the rest.
A hand-written union scatters the set
TypeScript already models a closed set as a discriminated union, and a base type for the fields every variant holds:
type Base = { id: string };
type Circle = Base & { _tag: "Circle"; r: number };
type Square = Base & { _tag: "Square"; side: number };
type Shape = Circle | Square;
Adding Triangle is three edits: a new type, a new arm on the union, and & Base again. Forget the
last one and the declaration still compiles. TypeScript reports it at the first shape.id, not at
the variant missing & Base.
A new variant breaks a switch silently
A switch on the tag narrows, and a missing case is an error where the return type is annotated and
every arm returns. A switch that runs side effects has neither, so adding Triangle compiles:
type Triangle = { _tag: "Triangle"; base: number; height: number };
type Shape = Circle | Square | Triangle;
function draw(shape: Shape) {
switch (shape._tag) {
case "Circle":
drawCircle(shape);
break;
case "Square":
drawSquare(shape);
break;
}
}
A triangle draws nothing, and no type says so. You write the check yourself: assertNever(shape)
under a default, and a break closing every case. strict reports neither a missing case nor a
missing break. noFallthroughCasesInSwitch catches the second, and the lint rule
typescript/switch-exhaustiveness-check catches the first, once you enable both.
Declare variants in Enum<...> and create their companion with Enum.companion<E>().build().
companion.match(value, handlers) requires a handler for every variant, or _ for the rest.
Enums covers shared fields, custom seals and tags:
type Shape = Enum<"Shape", { Circle: { r: number }; Square: { side: number } }>;
const Shape = Enum.companion<Shape>().build();
const area = Shape.match(Shape.Circle.create({ r: 2 }), {
Circle: (circle) => Math.PI * circle.r * circle.r,
Square: (square) => square.side * square.side,
});
Traits
A trait declares the fields and functions that several Vals share.
A function does not declare a contract
A function can accept the fields it reads, and every type holding them fits:
type User = { id: string; name: string };
type Admin = { name: string; level: number };
function greet(greetable: { name: string }): string {
return `Hi, ${greetable.name}`;
}
The parameter is the contract, written again in every function that wants it. Rename a field and the type remains valid. The function remains valid. Only a call fails.
The error lands away from the type that broke it:
greet(user); // type error: User has no `name` any more
A companion collects one Val’s functions, but does not declare behavior shared by other Vals. A trait declares shared fields and functions once. Each implementing Val points to that declaration, so a renamed field fails at the Val that broke the contract.
const admin = Admin.seal({ name: "root", level: 9 });
User.greet(admin); // type error: greet belongs to User
Admin holds the name that greet reads, and User.greet rejects it all the same. Collecting
behavior and sharing it are still two different things.
Declare a Trait, add it to a Val’s third type argument, then register its members with
.implTrait. Traits covers defaults, enums and dyn:
type Describable = Trait<"Describable", { name: string }, { describe: (self: Self) => string }>;
const Describable = Trait.companion<Describable>().build();
type User = Val<"User", { name: string }, Describable>;
const User = Val.companion<User>()
.implTrait(Describable, () => ({ describe: (user) => user.name }))
.build();
-
A
createregistered with.implCreate.nosealskips the seal in production. ↩
Installation
npm install valof
The recommended compiler options are:
strict(the default since TypeScript 6)exactOptionalPropertyTypes
Without exactOptionalPropertyTypes, { a?: string } also accepts undefined, even though JSON
serialization drops that key.
Val
A Val is a branded, immutable type over plain data.
For the problem that branding solves, see TypeScript Problems Valof Addresses.
Define branded types
Val takes the brand and the payload type:
import { Val } from "valof";
type UserId = Val<"UserId", string>;
type OrderId = Val<"OrderId", string>;
The brand is phantom. A UserId is still a string at runtime.
Name the brand after the type it brands: type UserId = Val<"UserId", string>. The
brand-mismatch lint rule reports when the names do not match.
Construct values
Val.companion creates the type’s companion. Its seal brands a payload:
const UserId = Val.companion<UserId>().build();
const OrderId = Val.companion<OrderId>().build();
const userId = UserId.seal("u_1");
let orderId: OrderId;
orderId = userId; // type error: UserId is not an OrderId
orderId = "o_1"; // type error: a plain string is not an OrderId
type User = Val<"User", { name: string }>;
const User = Val.companion<User>().build();
const user = User.seal({ name: "alice" });
// @ts-expect-error spread drops the brand
const changed: User = { ...user, name: "bob" };
const resealed = User.seal({ ...user, name: "bob" });
Name the companion after its type: const UserId = Val.companion<UserId>().build(). TypeScript lets
the type and value share a name. The companion-mismatch lint rule reports when
they do not match.
Immutability
Readonly<T> only protects the top-level properties. It also cannot prevent a value from changing
through the original reference:
type Profile = Readonly<{
name: string;
address: { city: string };
}>;
const raw = { name: "alice", address: { city: "Osaka" } };
const profile: Profile = raw;
profile.name = "mallory"; // type error: the top-level property is readonly
profile.address.city = "Tokyo"; // allowed: Readonly is shallow
raw.name = "mallory"; // allowed: raw is still writable
A recursive readonly type prevents the nested write, but the original reference remains writable. Keeping a value unchanged requires both deep readonly types and a copy at construction.
Vals are immutable
Vals are immutable. Their types are deeply readonly, and their constructors deep-copy their inputs. The copy skips anything already inside a Val, such as a nested Val or a branch taken from an existing Val:
type Profile = Val<"Profile", { name: string; address: { city: string } }>;
const Profile = Val.companion<Profile>().build();
const raw = { name: "alice", address: { city: "Osaka" } };
const profile = Profile.seal(raw);
profile.address.city = "Tokyo"; // type error: Vals are deeply readonly
raw.address.city = "Tokyo";
profile.address.city; // "Osaka"
const renamed = Profile.seal({ ...profile, name: "bob" });
renamed.address === profile.address; // true: not copied again
Val makes the payload deeply readonly:
type Post = Val<"Post", { tags: string[] }>;
declare const post: Post;
post.tags.push("typescript"); // type error: tags is readonly
readonly exists only in the type system. In development, Valof also freezes values, so a write
that uses a cast to bypass the type throws where it happens. Production builds skip the freeze. Some
generic object utilities, such as Object.assign, write to a Val without a cast. See
Caveats.
Only primitives, arrays and plain objects can live inside a Val. See Allowed Types.
Avoid a copy with .nocopy
.nocopy uses the payload as the value, without copying it. The default copy already skips anything
inside a Val, so use .nocopy only where profiling shows the copy is a bottleneck.
Warning
.nocopyis an explicit escape hatch. You must ensure the value and everything inside it is stable plain data with no mutable aliases. If that is wrong, another reference can change a Val in production. Prefer the default copy whenever there is doubt.
Only when you can make that guarantee, use .nocopy:
import { Val } from "valof";
type Profile = Val<"Profile", { name: string; address: { city: string } }>;
const Profile = Val.companion<Profile>().build();
const seed = { name: "alice", address: { city: "Osaka" } } as const;
const profile = Profile.seal.nocopy(seed);
The common trap is a mutable alias behind a readonly view:
const mutable = { name: "alice", address: { city: "Osaka" } };
const seed: SeedOf<Profile> = mutable; // TypeScript permits this readonly view.
const profile = Profile.seal.nocopy(seed);
// In production, this also changes `profile.address.city`.
// Development freezing normally makes this assignment throw instead.
mutable.address.city = "Tokyo";
readonly is only a guardrail. Mutable views, casts, accessors and proxies can still break this
contract. The default seal’s nocopy requires deeply readonly input. Val.of.nocopy<V> and custom
seals leave the responsibility to their callers and implementations. Development validates and
freezes the payload, and production trusts the contract. patch still copies.
Allowed Types
Only three things can be a payload:
| Primitives | string / number / boolean / bigint; null below the top level |
| Arrays | allowed[], or a tuple: [allowed, allowed] |
| Objects | { k: allowed }, or Record<string, allowed> |
A Val is itself one of these, so Vals nest. A tuple keeps its positions and its length. One with a
rest element ([string, ...number[]]) reads as an array instead, since a fixed length is what
distinguishes the two.
Write the payload plain
Val makes the payload deeply readonly on its own, so readonly in the definition changes nothing
about the value. Writing it makes Val.unwrap return a readonly payload,
which is what unwrap exists to avoid.
type Post = Val<"Post", { tags: string[] }>; // not `readonly string[]`
post.tags; // readonly string[] all the same
Val.unwrap(post).tags.sort(); // ✓ returns a mutable `string[]`
Classes and functions
Neither a class instance nor a function can be a payload. Date, Temporal, Map and Set are
all classes. See Dates and Map / Set instead.
TypeScript rejects them, on the first use of the Val rather than on the type line.
A class of plain fields is the one TypeScript cannot distinguish from an object, and sealing one throws in development.
A type that references itself
A tree holds trees. Write the self-reference as Rec<Tree>.
type Tree = Val<"Tree", { value: number; children: Rec<Tree>[] }>;
const Tree = Val.companion<Tree>().build();
const leaf = Tree.seal({ value: 1, children: [] });
const root = Tree.seal({ value: 2, children: [leaf] });
root.children[0]; // Tree
Rec is erased. The value holds a Tree, and the constructor takes one. It exists for the
declaration alone.
Without it the declaration compiles and the first use of the type fails.
type Tree = Val<"Tree", { value: number; children: Tree[] }>;
const Tree = Val.companion<Tree>().build();
The Default Companion
Val.companion<V>().build() returns the default companion: seal, and
patch for a Val that holds an object payload.
The steps between Val.companion and .build() replace seal or add functions to the companion.
Write .implSeal first, then .implCreate. .impl, .implTrait and .implAssoc come next, in
any order. .impl is written once.
- Adding Functions to the Companion covers
.impland.implAssoc. - Custom Constructors and Invariants covers
.implSealand.implCreate. - Traits covers
.implTrait.
Patch object values
Without Valof, changing a deeply readonly shop means rebuilding every object on the path:
const changed = {
...shop,
owner: {
...shop.owner,
contact: {
...shop.owner.contact,
email: "e@example.com",
},
},
};
With patch, the same update lists only what changes:
const changed = Shop.patch(shop, {
owner: { contact: { email: "e@example.com" } },
});
A patch expresses three operations:
- Omit a key to leave it unchanged.
- Pass
{ k: undefined }to delete it. - Pass
{ k: value }to set it.
With exactOptionalPropertyTypes, { k: undefined } is accepted only for optional keys. Without
it, TypeScript also accepts it for required keys, and patch deletes them at runtime.
A patch reaches through nested plain objects, but replaces a nested Val, an array or a primitive whole:
Shop.patch(shop, { city: City.patch(shop.city, { name: "Osaka" }) });
Derive a nested Val with its own patch, so its own seal checks the change.
Like seal, patch reuses what is already inside the Val. It
copies only the path to what changed, and untouched branches keep their reference identity:
changed.city === shop.city; // true
Shop.patch(shop, {}) === shop; // true
Reference comparisons, such as React dependency arrays, can then skip work when their value did not change.
Adding Functions to the Companion
For the limits of standalone functions and classes, see TypeScript Problems Valof Addresses.
Add functions that take the Val
Valof collects the constructor and functions under a value with the same name as the type:
type User = Val<"User", { id: string; name: string; nickname?: string }>;
const User = Val.companion<User>()
.impl(() => ({
displayName(user) {
return user.nickname ?? user.name;
},
// A member calling another member annotates its return type, to avoid an implicit `any`.
formatLabel(user, separator: string): string {
return user.id + separator + User.displayName(user);
},
}))
.build();
.impl(() => ({ ... })) adds member functions to the companion. Every .impl member takes its Val
first, so Valof infers that parameter as User. You only annotate the parameters that follow it,
and the return type where a member references User itself.
The function passed to .impl receives seal, create where
.implCreate registered one, and patch for
a Val that holds an object payload. A member calling them does not reference User, so its return
type needs no annotation.
The companion exposes seal and the members:
const user = User.seal({ id: "a", name: "bob" });
User.displayName(user);
User.formatLabel(user, ": ");
Add functions that do not take the Val
.implAssoc registers a function that does not take the Val as its first argument:
type User = Val<"User", { id: string; name: string }>;
const User = Val.companion<User>()
.implAssoc(() => ({
names: (users: readonly User[]) => users.map((user) => user.name),
}))
.build();
User.names([User.seal({ id: "a", name: "bob" })]); // ["bob"]
The function passed to .implAssoc receives the same seal, create and patch as the one passed
to .impl, so its members can build the Val. A member that builds the Val is a constructor. See
Define other constructors with implAssoc.
Call a member with the value last
Vals are plain data, so their members cannot be chained like methods. Instead, a member taking more than one argument can be called with the value last, which is the form a pipeline expects. A member taking only the value is passed as it is:
User.formatLabel(user, ": "); // "a: bob"
User.formatLabel(": ")(user); // "a: bob"
pipe(user, User.patch({ nickname: "b" }), User.displayName); // "b"
patch, a trait’s member taking more than one argument, an enum’s match and [Tag].match can be
called either way too. Valof ships no pipe. Use the one from your favorite library.
A member cannot have an optional, a default or a rest parameter. Pass undefined where an argument
has no value.
Custom Constructors and Invariants
Without .implSeal, a companion’s seal accepts every payload allowed by the type. When
construction has rules of its own, replace it with .implSeal. Every other constructor passes its
payload to that seal, so the seal checks every Val the companion builds.
Validate in the seal
Write the checks directly in the seal:
type Age = Val<"Age", number>;
const Age = Val.companion<Age>()
.implSeal((value, seal): Result<Age> =>
value >= 0 && Number.isInteger(value)
? ok(seal(value))
: err("age must be a non-negative integer"),
)
.build();
The custom seal receives the default seal as its second argument, and brands and copies the payload through it.
Age.seal.nocopy(value) runs exactly the same validation and normalization, but does not copy the
payload passed to the default seal inside the custom seal. It carries the caller contract
described in Immutability.
Valof provides no Result type. Use one from a library such as
byethrow, or your own. Valof propagates the seal’s return
type without inspecting it.
A schema library can parse a wider input before calling the default seal:
const schema = z.object({ id: z.uuid(), name: z.string().min(1), email: z.email().toLowerCase() });
const User = Val.companion<User>()
.implSeal((input: object, seal): Result<User> => {
const result = schema.safeParse(input);
return result.success ? ok(seal(result.data)) : err(z.prettifyError(result.error));
})
.build();
The parameter can be typed object or Record<string, unknown>, but not unknown. A seal takes
the payload, not a wire format.
The schema runs on every derivation, not just the first parse. Reject unknown keys yourself. A patch is merged as given, so an undeclared key survives unless the seal removes it.
Normalize in the seal
Normalize in the seal so equivalent inputs have the same canonical form:
type Email = Val<"Email", string>;
const Email = Val.companion<Email>()
.implSeal((value, seal) => seal(value.trim().toLowerCase()))
.build();
Canonical payloads make structural equals match what equality means in your
domain.
Generate fields with create
create builds a payload, then passes it to the seal:
const User = Val.companion<User>()
.implSeal((user): Result<User> => check(user))
.implCreate((fields: Fields) => ({ id: crypto.randomUUID(), ...fields }))
.build();
User.create(fields); // Result<User>
create.nocopy(...args) reuses the registered create function and seal, but does not copy the
payload. It carries the same caller contract as seal.nocopy.
A seal must be idempotent. patch on a Val that holds an object payload and any registered
create pass their payloads through your seal. Sealing a value’s own payload must return that
value. Generate an id or timestamp in create, not in seal.
Bypass the seal in create
A create whose payload the seal always accepts never fails, but it still returns the seal’s
Result or | undefined. .implCreate.noseal bypasses the seal and returns the Val:
type SessionId = Val<"SessionId", string>;
const SessionId = Val.companion<SessionId>()
.implSeal((text, seal): SessionId | undefined => (UUID.test(text) ? seal(text) : undefined))
.implCreate.noseal(() => crypto.randomUUID())
.build();
SessionId.create(); // SessionId
SessionId.seal(input); // SessionId | undefined
.implCreate.noseal takes no arguments. A payload that depends on arguments should pass through the
seal to be normalized. The function passed to .noseal must always return a canonical payload. In
production, create skips the custom seal. It still copies the payload, skipping anything already
inside a Val, as seal does. In development, it runs the seal
and throws if the seal rejects or normalizes the payload.
Define other constructors with implAssoc
.implAssoc registers a function that
builds the Val from something else, such as a string or several other values:
type Yen = Val<"Yen", number>;
const Yen = Val.companion<Yen>()
.implSeal((yen, seal): Result<Yen> =>
Number.isSafeInteger(yen) && yen >= 0
? ok(seal(yen))
: err("must be a non-negative safe integer"),
)
.implAssoc(({ seal }) => ({
parse: (text: string): Result<Yen> =>
/^¥\d+$/.test(text) ? seal(Number(text.slice(1))) : err("expected ¥ followed by digits"),
sum: (yens: readonly Yen[]) => seal(yens.reduce((total, yen) => total + yen, 0)),
}))
.build();
Yen.parse("¥120"); // Ok
Yen.parse("¥99999999999999999"); // Err("must be a non-negative safe integer")
Yen.sum(yens); // Result<Yen>
Keep an invariant in the seal, and let a member only convert its input into a payload. parse
checks the string’s format, and the seal checks the amount. A check written in a member does not run
when another path builds the value, such as patch on an object payload.
Restrict the companion with options
Options in the second type argument of Val.companion restrict what the companion offers callers.
Any of them can be combined.
create can generate an id. PrivateSeal removes seal from the companion, so a caller cannot
pass an id of their own. Unpatchable excludes keys from patch, so an id keeps the value create
generated:
type User = Val<"User", { id: string; name: string }>;
const User = Val.companion<User, [PrivateSeal, Unpatchable<"id">]>()
.implCreate((name: string) => ({ id: crypto.randomUUID(), name }))
.build();
User.create("sue"); // User
User.seal({ id: "forged", name: "sue" }); // type error
User.patch(user, { name: "sue" }); // OK
User.patch(user, { id: "forged" }); // type error
PrivateCreate removes create from the companion. Use it when callers should build the type
through seal or other functions, not create. It protects no field, because the payload create
returns passes the seal.
The function passed to .impl, .implTrait and .implAssoc
still receives seal and create, so the companion’s own members can build the type.
Parse, don’t validate
A validator checks its input but returns no more precise value:
const valid = isValidInterval(input); // boolean; input is still a string
The type records nothing that the validator learned. Each consumer must trust that the check ran or repeat it. This spreads validation through processing code, an anti-pattern called shotgun parsing.
A parser instead turns less precise input into more precise output, or returns a failure. Parsing a wire format into a Val takes two steps:
- Decode the wire format into the payload’s shape:
"1..10"into{ min: 1, max: 10 }. An.implAssocmember does this. - Seal the payload into the Val: check the invariants, normalize, and brand. Only the seal does
this, because
create,patchand the.implAssocmembers pass their payloads to it.
Interval.parse takes both steps, and create and patch reach the same seal:
type Interval = Val<"Interval", { min: number; max: number }>;
const Interval = Val.companion<Interval>()
.implSeal((interval, seal): Result<Interval> =>
interval.min <= interval.max ? ok(seal(interval)) : err("min must not exceed max"),
)
.implCreate((size: number) => ({ min: 0, max: size }))
.implAssoc(({ seal }) => ({
parse: (text: string): Result<Interval> => {
const match = /^(\d+)\.\.(\d+)$/.exec(text);
return match
? seal({ min: Number(match[1]), max: Number(match[2]) })
: err("expected min..max");
},
}))
.build();
Interval.parse("1..10"); // Ok
Interval.parse("1-10"); // Err("expected min..max")
Interval.parse("10..1"); // Err("min must not exceed max")
Interval.create(5); // Ok
Interval.patch(interval, { max: -1 }); // Err("min must not exceed max")
Once a value has been successfully sealed as an Interval, its type guarantees that it is validated
and normalized wherever it is passed, so downstream code does not need to repeat either step. The
seals on this page put
“parse, don’t validate”
into practice. They return a validated, canonical Val instead of returning facts about the input.
Parsing includes validation, but preserves its result in a more precise type. In Takuto Wada’s
words,
parse, don’t (just) validate:
the Interval type can now represent only valid intervals. create and patch reuse the same
parser.
Enums
An enum is a discriminated union declared in one place. Each variant is a Val, and the enum is the union of those Vals. The variants form a closed set, so TypeScript can check that every variant is handled.
For the limits of a hand-written discriminated union, see TypeScript Problems Valof Addresses.
Declare the variants
import { Enum, equals } from "valof";
type Shape = Enum<"Shape", { Circle: { r: number }; Square: { side: number } }>;
const Shape = Enum.companion<Shape>().build();
const circle = Shape.Circle.create({ r: 2 }); // { r: 2, _tag: "Circle" }
Shape.Circle.patch(circle, { r: 5 }); // { r: 5, _tag: "Circle" }, the tag stays
equals(circle, Shape.Circle.seal({ _tag: "Circle", r: 2 })); // true
Each key of the second type argument is a variant, and its value is that variant’s payload. Valof derives the union and each variant’s brand from this one declaration. To add a variant, add a key to this declaration.
Call a variant through the companion, as in Shape.Circle.create(…).
The default create takes every field except the tag. It adds the tag field and passes the payload
to the variant’s seal. The seal takes a payload that includes the tag field. To build a value from a
tag alone, see Shape[Tag].match.
patch cannot change the tag, so it cannot turn a value into another variant.
Declare at least two variants. Enum rejects a declaration with one variant, because one variant is
a Val.
Match on the tag
const area = Shape.match(shape, {
Circle: (c) => Math.PI * c.r * c.r,
Square: (s) => s.side * s.side,
});
Each handler receives its own variant. Without _, match requires a handler for every variant.
Adding a variant to the declaration then causes a type error here until the variant has a handler,
rather than falling through at run time. You write no break or assertNever, and enable no lint
rule. match returns the union of the handlers’ return types.
_ handles the variants that have no handler of their own.1 Its argument is narrowed to
those variants:
const size = Shape.match(shape, {
Circle: (c) => c.r,
_: (rest) => rest.side,
});
_ also handles a variant added to the declaration later, with no type error.
Build a value from a payload or a tag
An enum value can be built from three kinds of input, and each has its own call:
| When you have | Use |
|---|---|
| the fields of a variant you already know | Shape.Circle.create(fields) |
| a payload including its tag, such as a schema library’s output | Shape.seal(payload) |
| the tag alone, with the fields kept elsewhere | Shape[Tag].match(tag, handlers) |
The default Shape.seal(payload) reads the tag, selects that variant, and passes the payload to the
variant’s seal. When you know which variant the payload is, call that variant’s seal, as in
Shape.Circle.seal(payload).
When you have the tag alone, Shape[Tag].match calls the handler for that tag. For example, the
first argument on a command line is a subcommand, and the subcommand decides how to read the
remaining arguments:
type Command = Enum<
"Command",
{ New: { name: string }; Rename: { from: string; to: string }; Check: Record<never, never> }
>;
const Command = Enum.companion<Command>().build();
// The subcommand, already normalized to its tag, and the arguments after it.
declare const input: { tag: "New" | "Rename" | "Check"; args: readonly string[] };
const command = Command[Tag].match(input.tag, {
New: () => Command.New.create({ name: input.args[0] ?? "" }),
Rename: () => Command.Rename.create({ from: input.args[0] ?? "", to: input.args[1] ?? "" }),
Check: () => Command.Check.create({}),
});
As with match, every tag in the argument’s type needs a handler, or _ handles the rest. Without
_, adding a variant to the declaration causes a type error here too.
Share fields across variants
The third type argument of Enum is the shape, which lists the fields that every variant has. A
trait takes the same shape, as its second type argument.
type Task = Enum<"Task", { Todo: { text: string }; Done: { at: number } }, { id: string }>;
const Task = Enum.companion<Task>().build();
const todo = Task.Todo.create({ id: "t1", text: "write the docs" });
console.log(todo.id); // t1
Every variant’s create and seal require those fields. A value of the union type has them, so you
can read them without narrowing it.
The third type argument also declares the traits that the enum implements. See Implement traits on an enum.
Rename the tag
The tag is real data, not a phantom type like the brand. It is serialized with the value, so you can rename it to the field name that an API already uses:
type Event = Enum<"Event", { Click: { x: number }; Key: { code: string } }, Tag<"kind">>;
const Event = Enum.companion<Event>().tag("kind").build();
Event.Click.create({ x: 1 }); // { x: 1, kind: "Click" }
Event[Tag].key; // "kind"
Tag is declared in the third type argument, beside the shared fields, because every variant has
the tag field. .tag is required for a renamed tag, and it rejects a misspelled name. With the
default tag, the builder has no .tag.
Event[Tag].key returns the tag field’s name. Pass it to a schema library that asks for the
discriminator.
Build the companion
You build the companion in one chain. .tag comes first if the enum has a custom
tag key. Each variant’s steps come next, under the variant’s name, as in .Circle.impl(…). The
enum’s own steps come after them, and .build() ends the chain.
type Shape = Enum<"Shape", { Circle: { r: number }; Square: { side: number } }>;
const Shape = Enum.companion<Shape>()
.Circle.impl(() => ({ diameter: (c) => c.r * 2 }))
.impl(() => ({
// Annotate the return type of a member that uses `match`, a variant or another member
// through the companion. Without it, the return type is an implicit `any`. The same applies
// to a variant's member.
area: (s): number =>
Shape.match(s, {
Circle: (c) => Math.PI * c.r * c.r,
Square: (q) => q.side * q.side,
}),
}))
.build();
Shape.Circle.diameter(Shape.Circle.create({ r: 2 })); // 4
A variant with no steps keeps the default companion. Write a variant’s steps, and then the enum’s,
in the same order as in Val.companion. After the first enum step, the
chain no longer offers the variants’ steps.
Check the payload
A variant’s .implSeal replaces the variant’s seal, as
on a Val. The tag is a field of the payload, so the
seal can check it like any other field:
type Shape = Enum<"Shape", { Circle: { r: number }; Square: { side: number } }>;
const Shape = Enum.companion<Shape>()
.Circle.implSeal((c, seal) => (c.r > 0 ? seal(c) : new Error("r must be positive")))
.build();
Shape.Circle.create({ r: 2 }); // VariantOf<Shape, "Circle"> | Error
Shape.Square.create({ side: 1 }); // VariantOf<Shape, "Square">
Register the enum’s .implSeal to check a payload that has not been validated, such as an object
from JSON.parse. It runs in Shape.seal before the tag selects a variant, so it can also reject a
tag that selects no variant:
const Shape = Enum.companion<Shape>()
.implSeal((input: object, seal) => {
const result = schema.safeParse(input);
return result.success ? seal(result.data) : result.error;
})
.build();
Shape.seal(JSON.parse('{ "_tag": "Triangle" }')); // the schema's Error
The seal that the enum’s .implSeal receives selects the variant and runs that variant’s seal. A
variant’s own seal, create and patch do not run the enum’s .implSeal.
Create a payload
Unlike its variants, the enum has no default create.
.implCreate replaces a variant’s create,
or adds one to the enum.
A function given to a variant’s .implCreate returns a payload without the tag field. Valof adds
the tag field before the variant’s seal receives the payload. A function given to the enum’s
.implCreate returns a payload with the tag field, and the enum’s seal receives it:
type Task = Enum<"Task", { Todo: { text: string }; Done: { at: number } }, { id: string }>;
const Task = Enum.companion<Task>()
.Todo.implCreate((text: string) => ({ id: crypto.randomUUID(), text }))
.implCreate((at: number) => ({ _tag: "Done" as const, id: crypto.randomUUID(), at }))
.build();
Task.Todo.create("write the docs"); // VariantOf<Task, "Todo">
Task.create(Date.now()); // Task
.implCreate.noseal also works on the enum.
Restrict the companion with options
Enum.companion takes the same
options as Val.companion, in its
second type argument. Unpatchable<"id"> excludes id from patch on every variant that has it:
type Order = Enum<
"Order",
{ Pending: { note: string }; Shipped: { note: string; shippedAt: number } },
{ id: string }
>;
const Order = Enum.companion<
Order,
[Unpatchable<"id">, VariantOptions<"Shipped", [Unpatchable<"shippedAt">]>]
>().build();
VariantOptions<"Shipped", […]> applies the options in its list to Shipped alone.
VariantOptions accepts Unpatchable and PrivateCreate, but not PrivateSeal.
PrivateSeal removes Order.seal and every variant’s seal, because Order.seal can build any
variant from its tag. PrivateCreate removes create, whether it is the default one or one
registered with .implCreate. On the enum, it removes Order.create and every variant’s create.
In VariantOptions, it removes that variant’s create.
Use a variant’s type
VariantOf is the type of one variant.
const area = ({ r }: VariantOf<Shape, "Circle">) => r * r * Math.PI;
-
For an enum that has a variant named
_, write[Otherwise]in place of_to handle the rest.Otherwiseis a symbol exported fromvalof. ↩
Traits
For the contract that a trait adds, see TypeScript Problems Valof Addresses.
Declare what Vals share
A trait declares the fields and the functions:
import { Trait, type Self } from "valof";
type Greetable = Trait<
"Greetable",
{ name: string },
{
greet: (self: Self) => string;
toWire: (self: Self, sep: string) => string;
}
>;
The second argument is the shape: the fields every implementing Val holds. It follows the same rules as a payload, so a shape no Val could ever hold is an error where it is written.
The third declares the functions. They become members of every companion that implements the trait, and they take the value first.
Self stands for the implementing Val. A member may take it, and may not return it. What returns a
Self is a constructor, and a trait has no brand to seal with.
Implement it on a Val
A Val declares its traits in the third argument, and its companion implements them:
const Greetable = Trait.companion<Greetable>().build();
type User = Val<"User", { id: string }, Greetable>;
const User = Val.companion<User>()
.implTrait(Greetable, () => ({
greet: (u) => `Hi, ${u.name}`,
toWire: (u, sep) => `${u.id}${sep}${u.name}`,
}))
.build();
User.greet(User.seal({ id: "a", name: "alice" })); // "Hi, alice"
const duck: Greetable = { name: "duck" }; // type error: only a Val declaring Greetable is assignable
Trait.companion<Greetable>().build() creates the trait’s companion, even for a trait that
implements nothing itself. implTrait takes it as the first argument, and a function returning the
trait’s members as the second.
A trait adds the fields it requires to the payload, so the User payload includes name without
listing it. A payload may list one of them again with the same or a narrower type. A conflicting
type is a type error.
The unimplemented-trait rule in valof-lint reports a Val that declared a trait and
never implemented it.
Give a default implementation
Every Val writing its own greet repeats the same line. A trait can implement a member itself,
reading the shape alone, and that becomes the default for every Val that does not replace it:
const Greetable = Trait.companion<Greetable>()
.impl(() => ({ greet: (g) => `Hi, ${g.name}` }))
.build();
type User = Val<"User", { id: string; name: string }, Greetable>;
const User = Val.companion<User>()
.implTrait(Greetable, () => ({
toWire: (u, sep) => `${u.id}${sep}${u.name}`,
}))
.build();
type Admin = Val<"Admin", { name: string; level: number }, Greetable>;
const Admin = Val.companion<Admin>()
.implTrait(Greetable, () => ({
toWire: (a, sep) => `admin${sep}${a.name}`,
greet: (a) => `Sir ${a.name}`,
}))
.build();
User.greet(User.seal({ id: "a", name: "alice" })); // "Hi, alice"
Admin.greet(Admin.seal({ name: "root", level: 9 })); // "Sir root"
The function returns the members the trait does not implement, as both Vals return toWire. It may
also return a default to replace it, as Admin replaces greet.
Forbid replacing a default with Final
Mark one Final:
type Greetable = Trait<
"Greetable",
{ name: string },
{
greet: (self: Self) => string;
shout: Final<(self: Self) => string>;
}
>;
const Greetable = Trait.companion<Greetable>()
.impl(() => ({
greet: (g) => `Hi, ${g.name}`, // a Val may replace this one
shout: (g) => g.name.toUpperCase(), // declared Final: no Val may
}))
.build();
type User = Val<"User", { id: string; name: string }, Greetable>;
const User = Val.companion<User>().implTrait(Greetable).build();
The trait implements both, so implTrait needs no second argument. A Val may still return greet
from the function to replace it. Returning shout is an error.
The trait’s companion exposes its Final members, but not its defaults. Greetable.shout(user) can
be called, and Greetable.greet is a type error, because calling a default through the trait would
run it even for a Val that replaced it. Call a default through the Val’s companion, which
dispatches.
A default calling a Final member references the trait and annotates its return type:
const Greetable = Trait.companion<Greetable>()
.impl(() => ({
shout: (g): string => g.name.toUpperCase(),
// A member referencing `Greetable` itself annotates its return type, to avoid an implicit `any`.
greet: (g): string => `Hi, ${Greetable.shout(g)}`,
}))
.build();
Implement traits on an enum
An enum implements each trait it declares over the union, with one implTrait per
trait. What differs per variant is a match inside the implementation:
type Describable = Trait<"Describable", { id: string }, { describe: (self: Self) => string }>;
const Describable = Trait.companion<Describable>().build();
type Cmd = Enum<"Cmd", { Add: { n: number }; Del: { at: number } }, Describable>;
const Cmd = Enum.companion<Cmd>()
.implTrait(Describable, () => ({
describe: (c): string => Cmd.match(c, { Add: (a) => `add ${a.n}`, Del: (d) => `del ${d.at}` }),
}))
.build();
Cmd.describe(Cmd.Add.create({ id: "c1", n: 2 })); // "add 2"
A trait’s fields become fields every variant shares. id comes from Describable, and Cmd.Add
requires it.
A trait intersected into one variant’s payload applies to that variant alone, and that variant implements it:
type Named = Trait<"Named", { label: string }, { named: (self: Self) => string }>;
const Named = Trait.companion<Named>().build();
type Item = Enum<"Item", { Book: { pages: number } & Named; Pen: { ink: string } }>;
const Item = Enum.companion<Item>()
.Book.implTrait(Named, () => ({ named: (b) => `${b.label}, ${b.pages} pages` }))
.build();
Item.Book.named(Item.Book.create({ label: "Dune", pages: 412 })); // "Dune, 412 pages"
Hold values of different types together
dyn pairs a value with one Val’s implementation, so values of different types share an array. The
concrete type is gone, and only the trait is left. This is inspired by Rust’s Box<dyn Trait>:
const party: Dyn<Greetable>[] = [
Greetable.dyn(User, User.seal({ id: "a", name: "alice" })),
Greetable.dyn(Admin, Admin.seal({ name: "root", level: 9 })),
];
party.map((p) => p.greet()); // ["Hi, alice", "Sir root"]
party.map((p) => p.name); // ["alice", "root"]: a trait field, read from the box
A box already holds the value, so its members take only the arguments after it. The trait’s fields
are readable on it, and a function taking Greetable accepts one. The Val’s own fields are not.
p.id is a type error, because dyn drops the concrete type.
A box is a proxy over its value, not a Val. It has its own identity, and it has no patch. A
payload cannot hold one.
The two arguments belong together. The companion has to match the value’s own type, so another Val’s companion is rejected.
An enum boxes the same way, through its own companion:
Describable.dyn(Cmd, Cmd.Add.create({ id: "c1", n: 2 })).
dyn selects the implementation from the companion passed to it. If an enum and its variant both
declared a trait, Named.dyn(Item, book) and Named.dyn(Item.Book, book) would call different
implementations, so a variant cannot declare a trait that the enum already declares.
A function over boxes is registered on the trait’s companion, with .implAssoc. implTrait does
not copy it onto a Val.
Implement several traits
Intersect them in the declaration, and implement each in its own step:
type Weighed = Trait<"Weighed", { kg: number }, { heavy: (self: Self) => boolean }>;
const Weighed = Trait.companion<Weighed>()
.impl(() => ({ heavy: (w) => w.kg > 10 }))
.build();
type Crate = Val<"Crate", { name: string; kg: number }, Greetable & Weighed>;
const Crate = Val.companion<Crate>().implTrait(Greetable).implTrait(Weighed).build();
const crate = Crate.seal({ name: "box", kg: 20 });
Greetable.dyn(Crate, crate).greet(); // "Hi, box"
Weighed.dyn(Crate, crate).heavy(); // true
Write &, not |.
Each trait boxes on its own. No two traits on one Val may declare the same member name.
Other Functions
equals
equals compares two Vals of the same type structurally and deeply:
import { equals, Val } from "valof";
type User = Val<"User", { id: string; profile: { name: string } }>;
const User = Val.companion<User>().build();
const a = User.seal({ id: "a", profile: { name: "alice" } });
const b = User.seal({ id: "a", profile: { name: "alice" } });
a === b; // false
equals(a, b); // true
The comparison:
- compares array elements in order
- is independent of object key order
- ignores keys whose value is
undefined({ a: undefined }equals{}) - treats
NaNas equal toNaN, and-0as equal to0
The first argument fixes the Val type accepted by the second, so comparing values with different brands is a type error.
equals always compares the stored structure. When different inputs mean the same value, normalize
them in the seal. When the comparison means
something other than value equality, give it a name in the companion.
Val.of
Brands a payload with the type named explicitly.
Val.of<User>({ id: "a", name: "alice" });
If the type has a seal of its own, use that instead. Val.of skips the checks as an escape
hatch. Linting reports misuse of it, such as calling Val.of on a type that has a
companion or specifying no type.
Val.unwrap
A plain, mutable deep copy of the payload, to pass to code that does not know about readonly. It
strips the brand at every depth.
const post = Post.seal({ title: "t", tags: ["a"] });
post.tags.sort(); // ✗ readonly string[] has no sort
Val.unwrap(post).tags.sort(); // ✓
It returns the payload as the type declares it, so a readonly written there survives the unwrap.
Write the payload plain. See Allowed Types.
Linting
Rules for the mistakes the type checker cannot catch. They run as a plugin for ESLint and Oxlint, and as a standalone command.
pnpm add -D oxc-parser # valof does not install it for you
Rules
| rule | reports | default |
|---|---|---|
unused-member | a member registered with .impl or .implTrait that nothing reads | warning |
duplicate-brand | a brand string claimed by more than one top-level alias | error |
brand-mismatch | a brand whose last segment is not the name of the type it brands | error |
unnecessary-alias | a type alias that is a second name for a Val, a Trait or an Enum | error |
unimplemented-trait | a Trait a Val or an Enum declares that its companion does not implement | error |
companion-mismatch | a companion, or a variant, bound to a name other than its own | error |
split-companion | a companion for a type that another file declares | error |
bypassed-companion | a Val.of for a type whose companion is how it is built | warning |
unnamed-of | a Val.of that names no type, taking one from its target | warning |
incomplete-disable | a disable comment leaving out the rules it silences, or its scope | error |
unused-disable | a disable comment naming a rule that reports nothing there | warning |
A rule warns where the code around the finding still works, and errors where a Val is broken: two
types the checker stops distinguishing, or a name that has to agree with another and does not.
incomplete-disable errors for a reason of its own. A comment naming no rule silences every one, a
rule added next year included.
The severity is what the plugin sets, and a project can give any rule its own. The command prints every finding the same way and exits 1 on any of them.
A member registered with .impl(() => ({…})) is not tree-shaken, and knip does not report it when
it becomes unused.
Disable comments
Silence one line with a comment above it,
// valof-lint-disable-next-line unused-member -- public API
shout: (u) => u.toUpperCase(),
or a whole file with one anywhere in it:
// valof-lint-disable-whole-file unused-member -- every export here is public API
// valof-lint-disable-all-whole-file -- generated, do not lint
Name the rules it silences, separated by a space or a comma. The comments follow two rules of their
own, incomplete-disable and unused-disable, which can be left out of a run or given a severity
like any other.
Plugin for ESLint and Oxlint
The same rules, one per finding kind. Each rule can be given its own severity, or turned off, by its
name. The project to read is one setting for all of them, a path or a list of them, and defaults to
src/**/*.ts. A path starting with ! is excluded from it.
ESLint needs a parser that reads your TypeScript.
// eslint.config.js
import valof from "valof/eslint-plugin";
export default [
{
plugins: { valof },
rules: { ...valof.configs.recommended.rules, "valof/unused-member": "off" },
settings: { valof: { project: ["src/**/*.ts", "!src/generated/**"] } },
},
];
Oxlint takes the same plugin, through its JS plugins.
// oxlint.config.ts
import { defineConfig } from "oxlint";
import valof from "valof/eslint-plugin";
export default defineConfig({
jsPlugins: ["valof/eslint-plugin"],
extends: [valof.configs.recommended],
rules: { "valof/unused-member": "off" },
settings: { valof: { project: "src" } },
});
CLI
pnpm exec valof-lint src # the whole project
pnpm exec valof-lint src src/billing/id.ts # report on the changed file
pnpm exec valof-lint 'src/**/*.ts' '!src/generated/**' # leave a generated tree out
| argument | what it is |
|---|---|
| the first path | the project to read, a directory or a glob |
| the paths after it | the files to report on, the whole project when there are none |
--project, --report-on | the same two by name, in either order. Either can be repeated, and takes !path |
--no-<rule> | a rule to leave out of the run, by the rule name in the finding |
A single file given as the project is refused, because a duplicate brand needs the other alias to be seen.
A !path is excluded wherever it is written, and is removed from the run rather than only from the
report, so what a generated tree declares no longer applies to the rest.
Patterns
Framework state
A value is a plain object, so a state container holds it as it stands. Replace it whole. The untouched subtrees keep their identity, so a dependency array detects no change.
const [shop, setShop] = useState(Shop.seal({ owner, city }));
setShop(Shop.patch(shop, { owner: { email: "e@example.com" } }));
useEffect(() => showMap(shop.city), [shop.city]); // the patch did not touch `city`: no re-run
Solid reads the same with createSignal, and takes the comparison directly:
createSignal(user, { equals }).
Svelte and Vue are deeply reactive by default, so ask for a shallow container. A deep one gives
your code a proxy in place of the value. patch rebuilds a changed value and its parents, and keeps
the untouched branches by reference. Given a proxy, it copies those branches as well.
Values are frozen in development, so Vue skips them and ref behaves like shallowRef until you
build for production. A write through Vue’s ref or Solid’s createStore then mutates the value
instead of throwing.
| framework | |
|---|---|
| React | useState |
| Solid | createSignal, not createStore |
| Svelte 5 | $state.raw, not $state |
| Vue | shallowRef, not ref |
Return payloads across serialization boundaries
Return the payload, not the value. A generated client derives its response type from the handler, so a Val there arrives on the other side already typed as one, without having passed through the seal.
app.get("/user/:id", (c) => {
const body: PayloadOf<User> = user; // the brand drops, the object is the same one
return c.json(body);
});
Now the other side cannot use what arrives until it seals it:
const plain = await res.json(); // the generated client types this as PayloadOf<User>
const bad: User = plain; // type error: the brand is missing
const user = User.seal(plain); // sealed, and now it is one
PayloadOf<V> removes the brand from the type, not from the value, so it costs nothing at run time.
A Val whose payload contains an array cannot be assigned to its PayloadOf. The value’s array is
readonly, while PayloadOf keeps the mutable array the type declares. Return the copy that
Val.unwrap makes instead:
type Post = Val<"Post", { title: string; tags: string[] }>;
const body: PayloadOf<Post> = post; // type error: tags is readonly
const copy: PayloadOf<Post> = Val.unwrap(post);
PayloadOf and Val.unwrap both remove the brand of a nested Val.
Persistence helpers can create the same hole.
Jotai’s atomWithStorage, for example, parses stored
JSON and returns it as the type inferred from its initial value. Store a PayloadOf<User>, then
seal it after reading.
Seal at the boundary, because the two sides deploy separately. The value was sealed by whichever build the server is running, and that seal may be older than yours.
Map / Set
Use an object’s properties.
type Tags = Val<"Tags", Record<string, true>>; // a Set
type PriceTable = Val<"PriceTable", Record<string, Money>>; // a Map
Use true rather than null for a set, so if (tags[key]) is the membership test.
equals ignores key order, so comparing two of them is set equality.
patch sets the entries it lists, and removes an entry set to undefined. Call seal to rebuild
the whole table.
PriceTable.patch(table, { apple: Money.seal({ amount: 120, currency: "JPY" }), fig: undefined });
PriceTable.seal(Object.fromEntries(Object.entries(table).filter(([, m]) => m.amount < 500)));
Dates
export type UnixEpochMs = Val<"UnixEpochMs", number>;
export const UnixEpochMs = Val.companion<UnixEpochMs>()
.impl(() => ({
showLocal(d) {
return Temporal.Instant.fromEpochMilliseconds(d).toLocaleString();
},
}))
.build();
Caveats
Generic object utilities can bypass readonly and sealing
Object.assign accepts a readonly object as its target, so this passes the type checker:
Object.assign(user, { name: "mallory" });
Object.defineProperty has the same problem. Valof freezes values in development, so both calls
throw there. Production skips the freeze, and they mutate the Val.
Other utilities return a new object but preserve the input type. Immer, for example, makes a readonly input writable inside a callback:
const changed = produce(user, (draft) => {
draft.name = "mallory";
}); // User
The result is still typed as User, although its seal never checked the change. Use User.patch to
derive a value instead:
const changed = User.patch(user, { name: "mallory" });
When an API mutates its input, pass it Val.unwrap(user). When it returns a new payload, pass that
payload to User.seal.
A __proto__ key survives sealing
Sealing keeps a __proto__ key as an own property, because it is a legal JSON key. That is inert
inside a value, but not in code that merges a payload with Object.assign or a recursive merge.
There, assigning the key sets a prototype instead of copying it. Sanitize untrusted input yourself.
Deeply nested payloads can overflow the stack
Copying and comparing are both recursive, so a payload a few thousand levels deep, or a cyclic one,
throws a RangeError. Handle that error when sealing or comparing values from untrusted input.
API Reference
Functions
| API | Description |
|---|---|
equals(a, b) | deeply compares two Vals of the same type |
Val.of<V>(value) | applies the default seal, branding the value as V |
Val.of.nocopy<V>(value) | the same, without copying the payload |
Val.unwrap(value) | returns a mutable copy of the payload |
Val Companion Builder
| Step | Description |
|---|---|
Val.companion<V, O?>() | starts a companion, with the default seal and the options O |
.implSeal(f) | registers a custom seal |
.implCreate(f) | registers a function that creates a payload |
.implCreate.noseal(f) | the same, bypassing the seal for a payload it always accepts |
.impl(f) | adds the members f returns |
.implTrait(Tr, f?) | implements a trait the type declares |
.implAssoc(f) | adds the members f returns, which do not take the Val first |
.build() | ends the chain, and returns the companion |
Write implSeal first, then implCreate. impl, implTrait and implAssoc come next, in any
order. implSeal, implCreate and impl are written once, and the other two any number of times.
The function passed to impl, implTrait and implAssoc receives seal, create and patch,
including the ones PrivateSeal and PrivateCreate remove from the companion. It receives create
only where implCreate registered one, and patch only for a Val that holds an object payload.
Val Companion Options
Val.companion accepts any of these options in its second type argument.
| Option | Description |
|---|---|
PrivateSeal | removes seal from the companion |
PrivateCreate | removes create from the companion |
Unpatchable<K> | excludes keys K from patch |
Val Companion
User stands for the companion that belongs to the User type.
| API | Description |
|---|---|
User.seal(value) | applies the seal registered with .implSeal(f), or the default one. Removed by PrivateSeal |
User.seal.nocopy(value) | the same, without copying the payload |
User.create(...args) | creates a payload with the function registered with .implCreate(f), then passes it to the seal |
User.create.nocopy(...args) | the same, without copying the payload |
User.patch(user, patch) | deeply merges the patch, then seals it. Only for an object payload |
User.[member](first, ...rest) | runs a member registered with .impl(f), .implTrait(Tr, f?) or .implAssoc(f) |
User.[member](...rest)(first) | the same, with the first argument last, for a member taking more than one argument |
Val Types
| Type | Description |
|---|---|
Val<K, T> | a branded value type |
AnyVal | a constraint over any Val |
SeedOf<V> | the payload accepted by seals |
PayloadOf<V> | the payload, with the brand removed at every depth |
Patch<T> | the patch accepted for a payload |
Rec<V> | a Val’s reference to itself, in its own payload |
CompanionBuilder<V> | a companion’s builder, with the steps it can still take |
Companion<V, M> | the companion .build() returns |
You never write the builder and companion types, here or for an enum or a trait. They are exported
so that your own .d.ts can reference them when you re-export a companion.
Enum Companion Builder
| Step | Description |
|---|---|
Enum.companion<E, O?>() | starts an enum’s companion, with the options O |
.tag(key) | names the tag field the companion writes |
.implSeal(f) | adds a seal. E.seal runs it before the tag selects a variant |
.implCreate(f) | registers E.create |
.implCreate.noseal(f) | the same, bypassing the seal for a payload it always accepts |
.impl(f) | adds the members f returns, which take the union |
.implTrait(Tr, f?) | implements a trait the enum declares |
.implAssoc(f) | adds the members f returns, which do not take the union first |
.[VariantName].implSeal(f) | replaces that variant’s seal |
.[VariantName].implCreate(f) | replaces that variant’s create |
.[VariantName].implCreate.noseal(f) | the same, bypassing the seal for a payload it always accepts |
.[VariantName].impl(f) | adds the members f returns, which take that variant |
.[VariantName].implTrait(Tr, f?) | implements a trait that variant declares |
.[VariantName].implAssoc(f) | adds the members f returns, which do not take that variant first |
.build() | ends the chain, and returns the companion |
.tag comes first if the enum has a custom tag key. Each variant’s steps follow, in the same order
as Val.companion‘s. The enum’s steps come after them, in that order. The first enum step removes
the variants’ steps from the chain.
The function passed to the enum’s impl, implTrait and implAssoc receives E.seal, and
E.create where the enum’s implCreate registered one. The function passed to a variant’s impl,
implTrait and implAssoc receives that variant’s seal, create and patch.
Enum Companion Options
Enum.companion accepts the companion options in its second type
argument. They apply to the enum and every variant. To configure a specific variant’s companion, add
VariantOptions:
| Option | Description |
|---|---|
VariantOptions<N, O> | adds options O for variant N: PrivateCreate and Unpatchable<K> |
Enum Companion
E stands for an enum’s companion, and [VariantName] for the name of one of its variants.
| API | Description |
|---|---|
E.match(value, handlers) | matches on a variant’s tag field, exhaustively or with _ for the rest |
E.match(handlers)(value) | the same, with the value last |
E.match(value, { [Otherwise]: f }) | the same as _, for an enum with a variant named _ |
E[Tag].match(tag, handlers) | matches on a tag string, the same way |
E[Tag].match(handlers)(tag) | the same, with the tag last, for every tag |
E[Tag].key | the tag field’s name |
E.seal(payload) | builds the variant that the payload’s tag selects. Removed by PrivateSeal |
E.create(...args) | creates a payload with the function registered with .implCreate(f), then passes it to E.seal |
E.[member](first, ...rest) | runs a member registered for the union with .impl(f), .implTrait(Tr, f?) or .implAssoc(f) |
E.[member](...rest)(first) | the same, with the first argument last, for a member taking more than one argument |
E.[VariantName].seal(payload) | builds that variant from a payload including its tag. Removed by PrivateSeal |
E.[VariantName].create(fields) | writes the tag and passes the payload to that variant’s seal. Removed by PrivateCreate |
E.[VariantName].create(...args) | the same, with the arguments of the function registered with .[VariantName].implCreate(f) |
E.[VariantName].patch(value, patch) | derives a value of that variant, keeping the tag |
E.[VariantName].[member](first, ...rest) | runs a member registered for that variant with .[VariantName].impl(f), .[VariantName].implTrait(Tr, f?) or .[VariantName].implAssoc(f) |
E.[VariantName].[member](...rest)(first) | the same, with the first argument last, for a member taking more than one argument |
Enum Types
| Type | Description |
|---|---|
Enum<K, D, X> | a closed set of variants, as one union |
Tag<T> | names the tag field, intersected into X |
VariantOf<E, N> | the type of one variant |
SeedFor<E, N> | what that variant’s create takes |
SealedPayload<E> | a tagged payload of one variant |
VariantsOf<E> / SharedOf<E> | the declared variants, and the shared fields |
NameOf<E> / TagOf<E> | the enum’s name, and the tag field’s name |
AnyEnum | a constraint over any enum |
EnumBuilder<E> | an enum’s builder, with the steps it can still take |
EnumCompanion<E> | the enum’s companion .build() returns |
Trait Companion Builder
| Step | Description |
|---|---|
Trait.companion<Tr>() | starts the trait’s own implementation |
.impl(f) | implements the members f returns, once |
.implAssoc(f) | adds the members f returns, which do not take a value implementing the trait first |
.build() | ends the chain, and returns the companion |
Members registered with implAssoc are not copied onto a Val by implTrait.
Trait Companion
| API | Description |
|---|---|
Tr.dyn(companion, value) | boxes a value with one Val’s implementation |
Tr.[member](first, ...rest) | runs a Final member registered with .impl(f), or one registered with .implAssoc(f) |
Tr.[member](...rest)(first) | the same, with the first argument last, for a member taking more than one argument |
Trait Types
| Type | Description |
|---|---|
Trait<K, Shape, M> | a contract Vals share |
Self | the implementing Val, inside a member’s signature |
Final<F> | marks a member no Val may replace |
Dyn<Tr> | a boxed value, with the concrete type gone |
AnyTrait | a constraint over any trait |
Members | the members a trait declares |
TraitBuilder<Tr> | a trait’s builder, with the steps it can still take |
TraitCompanion<Tr> | the trait’s companion .build() returns |