External data: parseJson<T>
Payloads from HTTP responses, files, or localStorage have whatever shape the sender wrote. Casting JSON.parse(text) as User bypasses checking entirely and moves the crash downstream. parseJson<T> validates untrusted data at the boundary using a validator generated directly from your TypeScript type.
In short
- Parse + validate in one call:
parseJson<User>(text)returns aResult<User, JsonError>. - Already parsed? (
await response.json(),MessageEvent.data): callvalidate<User>(value). - No
anyleaks: with@evobug_com/safe-ts-std/strict-lib,JSON.parsereturnsunknowninstead ofany(why). - Zero duplicate schemas: the build transform synthesizes the validator from your TypeScript type automatically.
Check it against the type
✕ Rejectedunhandled-failureno-unchecked-cast
ts
type User = { readonly id: string; readonly name: string };
export function loadUser(text: string): User {
return JSON.parse(text) as User;
}parseJson<T> checks the data against the type and returns a Result. The build writes the checking code from T, so there's no separate schema to keep in sync.
✓ Accepted0 diagnostics
ts
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr, type Option } from "@evobug_com/safe-ts-std/result";
export type User = {
readonly id: string;
readonly name: string;
readonly email: Option<string>;
readonly roles: readonly ("admin" | "editor")[];
};
export function loadUsers(text: string): JsonResult<readonly User[]> {
return parseJson<readonly User[]>(text);
}
export function describeUser(text: string): string {
const user = parseJson<User>(text);
if (isErr(user)) return `bad user data at ${user.error.path}: ${user.error.message}`;
return `${user.name} (${user.roles.length === 0 ? "no roles" : user.roles.join(", ")})`;
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr, type Option } from "@evobug_com/safe-ts-std/result";
export type User = {
readonly id: string;
readonly name: string;
readonly email: Option<string>;
readonly roles: readonly ("admin" | "editor")[];
};
export function loadUsers(text: string): JsonResult<readonly User[]> {
return __jsonParse<readonly User[]>(text, __va0);
}
export function describeUser(text: string): string {
const user = __jsonParse<User>(text, __v0);
if (isErr(user)) return `bad user data at ${user.error.path}: ${user.error.message}`;
return `${user.name} (${user.roles.length === 0 ? "no roles" : user.roles.join(", ")})`;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "id": string; "name": string; "email": (string) | (undefined); "roles": (("admin") | ("editor"))[]; };
function __va1(v: unknown, p: string): __JsonResult<(("admin") | ("editor"))[]> {
if (!Array.isArray(v)) return __jsonFail(p, "array", v);
const out: (("admin") | ("editor"))[] = [];
for (let __j13 = 0; __j13 < v.length; __j13++) {
const __j14: unknown = v[__j13];
let __j15!: ("admin") | ("editor");
__j16: {
if (__j14 === "admin") { __j15 = "admin"; break __j16; }
if (__j14 === "editor") { __j15 = "editor"; break __j16; }
return __jsonFail(p + "[" + __j13 + "]", "\"admin\" | \"editor\"", __j14);
}
out.push(__j15);
}
return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j4 = v["id"];
if (typeof __j4 !== "string") return __jsonFail(p + ".id", "string", __j4);
const __j5 = __j4;
const __j6 = v["name"];
if (typeof __j6 !== "string") return __jsonFail(p + ".name", "string", __j6);
const __j7 = __j6;
const __j8 = v["email"];
let __j9!: (string) | (undefined);
__j10: {
if (typeof __j8 === "string") { __j9 = __j8; break __j10; }
if (__j8 === undefined || __j8 === null) { __j9 = undefined; break __j10; }
return __jsonFail(p + ".email", "string | nothing", __j8);
}
const __j11 = v["roles"];
const __j17 = __va1(__j11, p + ".roles");
if (__jsonIsErr(__j17)) return __j17;
const __j12 = __j17;
const out: { "id": string; "name": string; "email": (string) | (undefined); "roles": (("admin") | ("editor"))[]; } = { "id": __j5, "name": __j7, "email": __j9, "roles": __j12 };
return out;
}
function __va0(v: unknown, p: string): __JsonResult<(__T0)[]> {
if (!Array.isArray(v)) return __jsonFail(p, "array", v);
const out: (__T0)[] = [];
for (let __j1 = 0; __j1 < v.length; __j1++) {
const __j2: unknown = v[__j1];
const __j18 = __v0(__j2, p + "[" + __j1 + "]");
if (__jsonIsErr(__j18)) return __j18;
const __j3 = __j18;
out.push(__j3);
}
return out;
}What you get:
- Errors that say where:
$.roles[1]: expected "admin" | "editor", got "root". Inside an optional object (or any union with one object type), the error comes from inside it:$.http.port: expected number | nothing, got "eighty". - Only the fields you declared: extra fields from outside are dropped, so they never sneak into your program (or reported, with
unknownKeys: "error"). nullbecomesundefinedforOption<T>and optional fields. Where a format'snullmeans something of its own,JsonNullandRawJsonkeep it.- Broken JSON is an error value, not an exception.
Data that's already parsed
For values you already have as objects (await response.json(), a message event), use validate<T>(value). They are unknown until then: unsafeAsync(() => response.json()) and the browser pack's json(response) give Result<unknown, ...>, a MessageEvent<unknown>'s data is unknown (no-hidden-any reports a MessageEvent without the type argument, whose data is any, and one whose type argument claims what was posted, MessageEvent<Order>). Both work with q(...) to pass the error up:
✓ Accepted0 diagnostics
ts
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import { q, type Result } from "@evobug_com/safe-ts-std/result";
type Order = { readonly id: string; readonly total: number };
export function orderTotal(message: unknown): Result<number, JsonError> {
const order = q(validate<Order>(message));
return order.total;
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q, type Result } from "@evobug_com/safe-ts-std/result";
type Order = { readonly id: string; readonly total: number };
export function orderTotal(message: unknown): Result<number, JsonError> {
const __q1 = __jsonValidate<Order>(message, __v0); if (__q1 instanceof __qErr) return __q1; const order = __q1;
return order.total;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "id": string; "total": number; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["id"];
if (typeof __j1 !== "string") return __jsonFail(p + ".id", "string", __j1);
const __j2 = __j1;
const __j3 = v["total"];
if (typeof __j3 !== "number") return __jsonFail(p + ".total", "number", __j3);
const __j4 = __j3;
const out: { "id": string; "total": number; } = { "id": __j2, "total": __j4 };
return out;
}Not a hand-written guard ((value: unknown): value is Order => "id" in value): TypeScript never checks a guard's body against its claim, so one that tests two fields of ten is a cast, and no-type-predicate reports it. validate tests every field the type declares and says which one is wrong.
Before or after a key conversion
The value must have the shape of the type you check it against. When a server sends snake_case keys and a helper turns them into camelCase (camelizeKeys, deepConvertKeys, an axios transformResponse), choose one side:
After the conversion, against the app's type. Usually the simpler choice: one type. Type the converter
(value: unknown) => unknown, so its output is still unchecked, and validate that:✓ Accepted0 diagnosticstsimport { type JsonResult, validate } from "@evobug_com/safe-ts-std/json"; type Roadmap = { readonly id: number; readonly createdAt: string; readonly issueIds: readonly number[] }; declare function camelizeKeys(value: unknown): unknown; export function readRoadmap(payload: unknown): JsonResult<Roadmap> { return validate<Roadmap>(camelizeKeys(payload)); }tsimport { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, validate } from "@evobug_com/safe-ts-std/json"; type Roadmap = { readonly id: number; readonly createdAt: string; readonly issueIds: readonly number[] }; declare function camelizeKeys(value: unknown): unknown; export function readRoadmap(payload: unknown): JsonResult<Roadmap> { return __jsonValidate<Roadmap>(camelizeKeys(payload), __v0); } // ---- generated by safe-ts: JSON validators ---- type __T0 = { "id": number; "createdAt": string; "issueIds": (number)[]; }; function __va0(v: unknown, p: string): __JsonResult<(number)[]> { if (!Array.isArray(v)) return __jsonFail(p, "array", v); const out: (number)[] = []; for (let __j7 = 0; __j7 < v.length; __j7++) { const __j8: unknown = v[__j7]; if (typeof __j8 !== "number") return __jsonFail(p + "[" + __j7 + "]", "number", __j8); const __j9 = __j8; out.push(__j9); } return out; } function __v0(v: unknown, p: string): __JsonResult<__T0> { if (!__jsonIsObject(v)) return __jsonFail(p, "object", v); const __j1 = v["id"]; if (typeof __j1 !== "number") return __jsonFail(p + ".id", "number", __j1); const __j2 = __j1; const __j3 = v["createdAt"]; if (typeof __j3 !== "string") return __jsonFail(p + ".createdAt", "string", __j3); const __j4 = __j3; const __j5 = v["issueIds"]; const __j10 = __va0(__j5, p + ".issueIds"); if (__jsonIsErr(__j10)) return __j10; const __j6 = __j10; const out: { "id": number; "createdAt": string; "issueIds": (number)[]; } = { "id": __j2, "createdAt": __j4, "issueIds": __j6 }; return out; }Before it, against a type of the wire (
created_at,issue_ids), followed by a typed function from the wire type to the app's. Worth it when the conversion does more than rename keys, or when you want the wire format written down.
Either way, the type describes JSON only. A type that also holds what the app adds after reading (a store, a function, a class instance) can't be validated: validate the JSON part and attach the rest afterwards.
Shared objects: validate to read, keep the raw object to write
validate<T> returns a copy with only the keys T lists. For an object other code also writes (history.state, which vue-router fills with keys of its own; a localStorage entry two features share; another library's options), writing that copy back deletes the other owner's keys. Validate to read, and write by changing the raw object's copy:
✓ Accepted0 diagnostics
ts
import { replaceState } from "@evobug_com/safe-ts-feature-browser/dom";
import type { DOMError } from "@evobug_com/safe-ts-feature-browser/errors";
import { validate } from "@evobug_com/safe-ts-std/json";
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";
type PanelState = { readonly panelScroll: number };
export function savedPanelScroll(): number {
const state = validate<PanelState>(history.state);
return isErr(state) ? 0 : state.panelScroll;
}
export function savePanelScroll(top: number): Result<void, DOMError<"DataCloneError" | "SecurityError">> {
// The router keeps its own keys in `history.state`: keep them, change ours.
const raw: unknown = history.state;
const base = typeof raw === "object" && raw !== null ? raw : {};
return replaceState(history, { ...base, panelScroll: top }, "");
}ts
import { replaceState } from "@evobug_com/safe-ts-feature-browser/dom";
import type { DOMError } from "@evobug_com/safe-ts-feature-browser/errors";
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { validate } from "@evobug_com/safe-ts-std/json";
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";
type PanelState = { readonly panelScroll: number };
export function savedPanelScroll(): number {
const state = __jsonValidate<PanelState>(history.state, __v0);
return isErr(state) ? 0 : state.panelScroll;
}
export function savePanelScroll(top: number): Result<void, DOMError<"DataCloneError" | "SecurityError">> {
// The router keeps its own keys in `history.state`: keep them, change ours.
const raw: unknown = history.state;
const base = typeof raw === "object" && raw !== null ? raw : {};
return replaceState(history, { ...base, panelScroll: top }, "");
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "panelScroll": number; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["panelScroll"];
if (typeof __j1 !== "number") return __jsonFail(p + ".panelScroll", "number", __j1);
const __j2 = __j1;
const out: { "panelScroll": number; } = { "panelScroll": __j2 };
return out;
}Unknown keys, and every problem at once
By default, keys the type doesn't list are dropped and checking stops at the first problem. Pass options as the second argument to change that, for parseJson and validate alike:
unknownKeys: "error"reports each key the type doesn't list, at its path ($.user.passwrd: unknown key). Handy for config files, where a typo would otherwise be silently ignored."drop"is the default.allErrors: truechecks everything, anderror.problemslists every problem (the first one is alsoerror.pathanderror.message, so code that reads those keeps working).compactchooses how big types are checked, see below.
✓ Accepted0 diagnostics
ts
import { parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Config = { readonly name: string; readonly port: number; readonly debug?: boolean };
export function configProblems(text: string): readonly string[] {
const config = parseJson<Config>(text, { unknownKeys: "error", allErrors: true });
if (!isErr(config)) return [];
return (config.error.problems ?? [config.error]).map((p) => `${p.path}: ${p.message}`);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, parseJsonOptionsWith as __jsonParseOptions, jsonFailInto as __jsonFailInto, jsonUnknownKey as __jsonUnknownKey, type JsonProblem as __JsonProblem } from "@evobug_com/safe-ts-std/json"; import { parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Config = { readonly name: string; readonly port: number; readonly debug?: boolean };
export function configProblems(text: string): readonly string[] {
const config = __jsonParseOptions<Config>(text, { unknownKeys: "error", allErrors: true }, __v0_sa);
if (!isErr(config)) return [];
return (config.error.problems ?? [config.error]).map((p) => `${p.path}: ${p.message}`);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "name": string; "port": number; "debug"?: boolean; };
function __va0_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<string> {
if (typeof v !== "string") return __jsonFailInto(e, p, "string", v);
const out = v;
return out;
}
function __va1_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<number> {
if (typeof v !== "number") return __jsonFailInto(e, p, "number", v);
const out = v;
return out;
}
function __va2_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<(boolean) | (undefined)> {
let out!: (boolean) | (undefined);
__j10: {
if (typeof v === "boolean") { out = v; break __j10; }
if (v === undefined || v === null) { out = undefined; break __j10; }
return __jsonFailInto(e, p, "boolean | nothing", v);
}
return out;
}
function __v0_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFailInto(e, p, "object", v);
let __j1: __JsonResult<never> | undefined;
const __j2 = v["name"];
const __j4 = __va0_sa(__j2, p + ".name", e);
if (__jsonIsErr(__j4)) __j1 = __j4;
const __j3 = __j4 as string;
const __j5 = v["port"];
const __j7 = __va1_sa(__j5, p + ".port", e);
if (__jsonIsErr(__j7)) __j1 = __j7;
const __j6 = __j7 as number;
const __j8 = v["debug"];
const __j11 = __va2_sa(__j8, p + ".debug", e);
if (__jsonIsErr(__j11)) __j1 = __j11;
const __j9 = __j11 as (boolean) | (undefined);
for (const __j12 of Object.keys(v)) { switch (__j12) { case "name": case "port": case "debug": break; default: __j1 = __jsonUnknownKey(p, __j12, e); } }
if (__j1 !== undefined) return __j1;
const out = { "name": __j3, "port": __j6 } as { "name": string; "port": number; "debug"?: boolean; };
if (__j9 !== undefined) out["debug"] = __j9;
return out;
}For {"name": 1, "prot": 80} that is $.name: expected string, got 1, $.port: expected number, got nothing and $.prot: unknown key.
Messages of your own: kind and expected
message is English. For messages in another language, or worded for a form, every problem (and the error itself, which is its first problem) also says what is wrong as data:
kind:"missing"(a required value isn't there),"wrongType"(the value isn't what the type asks for:nullfor a required field, a number out of anInt<Min, Max>range, a literal that isn't listed),"unknownKey","invalidJson", and forfromFields"duplicateKey"and"fieldCount";expected, formissingandwrongType: what the type asks for there, as in the message (number,"free" | "pro",integer from 1 to 12).
✓ Accepted0 diagnostics
ts
import { match } from "@evobug_com/safe-ts-std/enum";
import { type JsonProblem, validate } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Signup = { readonly email: string; readonly plan: "free" | "pro" };
function czech(problem: JsonProblem): string {
return match(problem.kind, {
missing: () => `${problem.path}: chybí`,
unknownKey: () => `${problem.path}: neznámé pole`,
_: () => `${problem.path}: má být ${problem.expected ?? "jiná hodnota"}`,
});
}
export function signupProblems(form: unknown): readonly string[] {
const signup = validate<Signup>(form, { unknownKeys: "error", allErrors: true });
return isErr(signup) ? (signup.error.problems ?? [signup.error]).map(czech) : [];
}ts
import { match } from "@evobug_com/safe-ts-std/enum";
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, validateOptionsWith as __jsonValidateOptions, jsonFailInto as __jsonFailInto, jsonUnknownKey as __jsonUnknownKey, type JsonProblem as __JsonProblem } from "@evobug_com/safe-ts-std/json"; import { type JsonProblem, validate } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Signup = { readonly email: string; readonly plan: "free" | "pro" };
function czech(problem: JsonProblem): string {
{ const __ms1 = problem.kind; let __mv1: string; switch (__ms1) {
case "missing": { __mv1 = `${problem.path}: chybí`; break; }
case "unknownKey": { __mv1 = `${problem.path}: neznámé pole`; break; }
default: { __mv1 = `${problem.path}: má být ${problem.expected ?? "jiná hodnota"}`; break; } } return __mv1; }
}
export function signupProblems(form: unknown): readonly string[] {
const signup = __jsonValidateOptions<Signup>(form, { unknownKeys: "error", allErrors: true }, __v0_sa);
return isErr(signup) ? (signup.error.problems ?? [signup.error]).map(czech) : [];
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "email": string; "plan": ("free") | ("pro"); };
function __va0_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<string> {
if (typeof v !== "string") return __jsonFailInto(e, p, "string", v);
const out = v;
return out;
}
function __va1_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<("free") | ("pro")> {
let out!: ("free") | ("pro");
__j7: {
if (v === "free") { out = "free"; break __j7; }
if (v === "pro") { out = "pro"; break __j7; }
return __jsonFailInto(e, p, "\"free\" | \"pro\"", v);
}
return out;
}
function __v0_sa(v: unknown, p: string, e: __JsonProblem[]): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFailInto(e, p, "object", v);
let __j1: __JsonResult<never> | undefined;
const __j2 = v["email"];
const __j4 = __va0_sa(__j2, p + ".email", e);
if (__jsonIsErr(__j4)) __j1 = __j4;
const __j3 = __j4 as string;
const __j5 = v["plan"];
const __j8 = __va1_sa(__j5, p + ".plan", e);
if (__jsonIsErr(__j8)) __j1 = __j8;
const __j6 = __j8 as ("free") | ("pro");
for (const __j9 of Object.keys(v)) { switch (__j9) { case "email": case "plan": break; default: __j1 = __jsonUnknownKey(p, __j9, e); } }
if (__j1 !== undefined) return __j1;
const out: { "email": string; "plan": ("free") | ("pro"); } = { "email": __j3, "plan": __j6 };
return out;
}The path says which field it is, so a message per field is a lookup by path.
NaN and Infinity in validate
JSON text can't hold NaN, Infinity or -Infinity, so parseJson never sees them. A value given to validate can hold them, and a number field accepts them. Pass finite: true to refuse them ($.x: expected finite number, got NaN):
✓ Accepted0 diagnostics
ts
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
type Position = { readonly x: number; readonly y: number };
export function readPosition(message: unknown): Result<Position, JsonError> {
return validate<Position>(message, { finite: true });
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, validateOptionsWith as __jsonValidateOptions } from "@evobug_com/safe-ts-std/json"; import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
type Position = { readonly x: number; readonly y: number };
export function readPosition(message: unknown): Result<Position, JsonError> {
return __jsonValidateOptions<Position>(message, { finite: true }, __v0_f);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "x": number; "y": number; };
function __v0_f(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["x"];
if (typeof __j1 !== "number" || !Number.isFinite(__j1)) return __jsonFail(p + ".x", "finite number", __j1);
const __j2 = __j1;
const __j3 = v["y"];
if (typeof __j3 !== "number" || !Number.isFinite(__j3)) return __jsonFail(p + ".y", "finite number", __j3);
const __j4 = __j3;
const out: { "x": number; "y": number; } = { "x": __j2, "y": __j4 };
return out;
}SafeInt and JsonValue always refuse them.
The validator is generated for the options, so write them as an object literal in the call; a variable is reported. Without allErrors, problems is absent. In a union, the problems come from inside the member the value fits by kind (an object, when the union has one object type; an array, when it has one array type); otherwise there is one problem for the union as a whole. With unknownKeys: "error", an object with a key a union member doesn't list doesn't match that member. Text that isn't JSON at all is one problem.
One validator per type
Each named type gets one validator per program, however many files check it. A file calling parseJson<User> imports User's validator from a module next to the file that declares User. User's validator imports Address's the same way, and the field checker of Audit when User extends Audit. Test-data generators (arbitrary<T>()) are shared the same way.
This shrinks apps with many API readers over the same types. An admin fixture with 12 readers over overlapping types (interfaces extending Audit, Money and Address in most of them, tagged unions, Page<T>), from a minified vite build:
| Validators per file | Shared | |
|---|---|---|
| Minified | 51.4 kB | 20.1 kB (−61%) |
| gzip | 6.2 kB | 4.7 kB (−25%) |
The fixture is in packages/safe-ts-transform/test/fixtures/admin, and node scripts/shared-validators-size.mjs measures it. Both bundles return the same results and errors for the same input.
What stays in the file that uses it, as before:
- anonymous types (
validate<{ id: string }>,parseJson<readonly User[]>: the array check stays, and it callsUser's shared validator); - types declared in a function or block, and types declared in a
.vuecomponent; - a generic type instantiated with one of those (
Page<Row>, withRowdeclared in the function); - every validator of a file that imports
parseJson/validatefrom somewhere other than@evobug_com/safe-ts-std/json(orarbitraryfrom other than@evobug_com/safe-ts-std/arbitrary). The shared modules import their helpers from there.
Each set of options gets its own validator: parseJson<User>(text, { allErrors: true }) uses a different one than parseJson<User>(text). Error messages and paths are the same either way. Where the modules are:
- Vite, Rolldown and Rollup:
types.ts?safe-ts-json=v$User, a module per type and set of options, generated from the types when the bundler loads it. The dev server rebuilds it whentypes.tschanges, or a type it builds on in another file. With Rollup, the TypeScript plugin must also accept these ids, since the module is TypeScript. - The Node loader: the same URLs, served by the loader and cached on disk like other files (Running TypeScript in Node). A resolve hook of your own sees these specifiers too, and must keep the
?safe-ts-json=query at the end (add an extension before it, not after). safe-ts emit:types.ts.safe-ts-json.tsnext to the emittedtypes.ts, with every validator the program uses fromtypes.ts.
safeTs({ sharedValidators: false }) (or SAFE_TS_SHARED_VALIDATORS=0 for the Node loader) gives every file its own copies again.
Big types: compact validators
A validator written out field by field is fast, and costs about 130–290 bytes of minified code per field. For a settings or rules object with hundreds of fields that adds up, in a bundle the browser loads first. A compact validator checks the object against a table instead: per field its key and a code for its type (string, number, boolean, SafeInt), or the validator of the field's type, read by one small std routine (jsonTable). Paths, messages, kinds, the result's key order and what unknownKeys, allErrors and finite do are the same.
- It is opt-in:
compact: truegives every object type in it a table (nested ones too). Without it (or withcompact: false) every one is written out, so no validator gets slower unless you ask. Like the other options, it goes in the call:validate<ShopSettings>(value, { compact: true }).
A shop's settings, 570 fields in 51 interfaces (50 sections of 11 fields and 20 fields of its own), with a plain and a strict, collecting validator, from a minified vite build (node scripts/compact-validators-size.mjs, Node 26; the validators' share of the bundle):
| Minified | gzip | Per field | validate, a valid value | |
|---|---|---|---|---|
| written out (default) | 163.4 kB | 21.4 kB | 287 B | 1.7 µs |
compact: true | 39.2 kB | 5.4 kB | 69 B | 14.9 µs |
So a table is about 4× smaller and up to 9× slower: every field is a lookup by a key the engine can't predict, where written-out code reads a known property. That suits data checked once (a config, the rules a page loads); for a type validated per message in a hot loop, leave it written out. Both bundles return the same results and errors for the same input.
Objects built from fields: fromFields
A table-driven decoder reads field names from a table at runtime, so it can't write an object literal, and packet[name] = value is a dictionary write (no-object-dictionary) that still needs a cast to become a Packet. fromFields<T>(keys, values) builds the T instead: keys[i] names the field values[i] goes in. The build generates a builder from T, like a validator:
Tis an object type, or a union of object types told apart by a field with a literal of its own in each (op,tag). That field is one of the pairs, and it picks the member.- Each value is checked against its field's type, as
validatechecks it. A required field without a value, a keyTdoesn't list, a key given twice, and more keys than values (or fewer) are errors. An optional field whose value isundefinedis left out. - The fields are written in
T's order into one object literal, so every object built for a member has the same shape. Keys in that order (the usual case, when they come from the same table as the type) cost one comparison each; any other order works too, a bit slower.
✓ Accepted0 diagnostics
ts
import { fromFields, type JsonError } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
export const Op = {
Hello: { code: 1, fields: { name: "string", version: "u8" } },
Ping: { code: 2, fields: {} },
} as const;
type OpName = keyof typeof Op;
type FieldType<D> = D extends "string" ? string : D extends "u8" ? number : never;
type PacketOf<O extends OpName> = { readonly op: O } & {
readonly [K in keyof (typeof Op)[O]["fields"]]: FieldType<(typeof Op)[O]["fields"][K]>;
};
export type Packet = { [O in OpName]: PacketOf<O> }[OpName];
/** `op`, then `Hello`'s fields in table order: what the reader decodes. */
const HELLO_KEYS = ["op", ...Object.keys(Op.Hello.fields)];
export function hello(name: string, version: number): Result<Packet, JsonError> {
return fromFields<Packet>(HELLO_KEYS, ["Hello", name, version]);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, jsonUnknownKey as __jsonUnknownKey, fromFieldsWith as __jsonFromFields, jsonDuplicateKey as __jsonDuplicateKey } from "@evobug_com/safe-ts-std/json"; import { fromFields, type JsonError } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
export const Op = {
Hello: { code: 1, fields: { name: "string", version: "u8" } },
Ping: { code: 2, fields: {} },
} as const;
type OpName = keyof typeof Op;
type FieldType<D> = D extends "string" ? string : D extends "u8" ? number : never;
type PacketOf<O extends OpName> = { readonly op: O } & {
readonly [K in keyof (typeof Op)[O]["fields"]]: FieldType<(typeof Op)[O]["fields"][K]>;
};
export type Packet = { [O in OpName]: PacketOf<O> }[OpName];
/** `op`, then `Hello`'s fields in table order: what the reader decodes. */
const HELLO_KEYS = ["op", ...Object.keys(Op.Hello.fields)];
export function hello(name: string, version: number): Result<Packet, JsonError> {
return __jsonFromFields<Packet>(HELLO_KEYS, ["Hello", name, version], __b0);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = (__T2) | (__T5);
type __T2 = { "op": "Hello"; "name": string; "version": number; };
type __T5 = { "op": "Ping"; };
function __b2(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<__T2> {
let __j3: unknown = undefined, __j4: unknown = undefined, __j5: unknown = undefined;
if (k.length === 3 && k[0] === "op" && k[1] === "name" && k[2] === "version") { __j3 = x[0]; __j4 = x[1]; __j5 = x[2]; } else {
const __j7: boolean[] = [];
for (let __j6 = 0; __j6 < k.length; __j6++) {
switch (k[__j6]) {
case "op": if (__j7[0] === true) return __jsonDuplicateKey(p, "op"); __j7[0] = true; __j3 = x[__j6]; break;
case "name": if (__j7[1] === true) return __jsonDuplicateKey(p, "name"); __j7[1] = true; __j4 = x[__j6]; break;
case "version": if (__j7[2] === true) return __jsonDuplicateKey(p, "version"); __j7[2] = true; __j5 = x[__j6]; break;
default: return __jsonUnknownKey(p, k[__j6] ?? "");
}
}
}
if (__j3 !== "Hello") return __jsonFail(p + ".op", "\"Hello\"", __j3);
const __j8 = "Hello";
if (typeof __j4 !== "string") return __jsonFail(p + ".name", "string", __j4);
const __j9 = __j4;
if (typeof __j5 !== "number") return __jsonFail(p + ".version", "number", __j5);
const __j10 = __j5;
const out: __T2 = { "op": __j8, "name": __j9, "version": __j10 };
return out;
}
function __b5(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<__T5> {
let __j11: unknown = undefined;
if (k.length === 1 && k[0] === "op") { __j11 = x[0]; } else {
const __j13: boolean[] = [];
for (let __j12 = 0; __j12 < k.length; __j12++) {
switch (k[__j12]) {
case "op": if (__j13[0] === true) return __jsonDuplicateKey(p, "op"); __j13[0] = true; __j11 = x[__j12]; break;
default: return __jsonUnknownKey(p, k[__j12] ?? "");
}
}
}
if (__j11 !== "Ping") return __jsonFail(p + ".op", "\"Ping\"", __j11);
const __j14 = "Ping";
const out: __T5 = { "op": __j14 };
return out;
}
function __b0(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<__T0> {
let __j1: unknown;
if (k[0] === "op") __j1 = x[0]; else { const __j2 = k.indexOf("op"); __j1 = __j2 < 0 ? undefined : x[__j2]; }
switch (__j1) {
case "Hello": return __b2(k, x, p);
case "Ping": return __b5(k, x, p);
default: return __jsonFail(p + ".op", "\"Hello\" | \"Ping\"", __j1);
}
}It returns a Result like validate: $.version: expected number, got "3", $.op: expected "Hello" | "Ping", got "Nope", $.extra: unknown key.
Building op and five fields (npm run bench:fields, Node 26, without the dev checks), relative to keyed stores into a fresh object and a cast, which is what a decoder does without fromFields:
| How | Time |
|---|---|
| a hand-written object literal per op, with a cast | 0.18–0.20× |
keyed stores (packet[name] = value) and a cast | 1× |
fromFields<Packet> | 1.01–1.03× |
Object.fromEntries, then validate<Packet> | 5.1–5.3× |
So the checks cost about nothing next to the keyed stores they replace, and the cast-free version is about 5× faster than Object.fromEntries plus a full validate. A hand-written literal per op is faster still, but it isn't table-driven.
Which types work
parseJson<T>, validate<T> and arbitrary<T>() accept the same types:
| Type | Notes |
|---|---|
string, number, boolean, undefined, literal types ("admin", 1, true) | number accepts NaN and ±Infinity in validate, unless finite: true |
SafeInt, bigint | integers past 2^53, see below |
Int<Min, Max> | a safe integer in a range, see below |
object types, interfaces (with extends too), intersections of object types | optional fields (field?:) may be missing or null |
arrays (T[], Array<T>, readonly T[], ReadonlyArray<T>), tuples | |
unions, Option<T>, Enum<...> | |
Readonly<T> | the same as T |
Record<K, V> with string literal keys | Record<"man" | "woman", number> is { man: number; woman: number }; K can be an alias |
Record<string, V>, { [key: string]: V }, Partial<Record<string, V>> | any keys, every value a V, see below |
typeof X, typeof X.member, computed keys ([Op.Hello]: string) | X is a const with a literal value (const FORMAT = "svg"), a declared type, as const, Object.freeze(…) of those, or a call of a function with a declared return type, see below |
keyof T, T["a"], T[keyof T], T[number] | on object types, and arrays and tuples, see below |
Partial, Required, Pick, Omit, Exclude, Extract, NonNullable | see below |
mapped types ({ [K in Keys]: V }, { [K in keyof T]?: T[K] }) | over string literal keys, string, or keyof an object type; as renames or drops keys, see below |
conditional types (T extends U ? X : Y), infer, T extends object, template literal types and patterns, tuple spreads and T["length"] | evaluated on the resolved types, see below |
JsonValue, unknown | any JSON, see below; unknown is checked the same way and typed unknown |
JsonNull, RawJson | a JSON null kept as null, and any JSON with its nulls kept, see below |
Open<K> | a string from a list that can grow: K a union of string literals; a string K doesn't list becomes Unknown instead of an error, see below |
Patch<T> | every field of T may be missing (keep it); one that may be missing in T may also be null (clear it), see Proof types |
| type aliases, interfaces | also imported (through export * and export { X } from too, through tsconfig.json paths aliases, and from workspace packages), declared in a function, generic and recursive |
namespace members (Backend.Models.User) | nested, merged with a type of the same name, global (declare global, a generated .d.ts) or exported from a module, see below |
Namespaces: generated model layers
A namespace member is a type like any other. Generated model layers (Rails serializers, GraphQL code generators) usually look like this: one declaration file per model, each continuing the global namespace Backend.Models.
✓ Accepted0 diagnostics
ts
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
// In a generated declaration file: `declare namespace Backend.Models { … }`.
declare global {
namespace Backend.Models {
interface User {
id: number;
name: string;
settings: Settings;
}
interface Settings {
generalTab: "profile" | "account" | "security";
}
}
}
type Tab = Backend.Models.User["settings"]["generalTab"];
export function readUser(text: string): JsonResult<Backend.Models.User> {
return parseJson<Backend.Models.User>(text);
}
export function readTab(text: string): JsonResult<Tab> {
return parseJson<Tab>(text);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
// In a generated declaration file: `declare namespace Backend.Models { … }`.
declare global {
namespace Backend.Models {
interface User {
id: number;
name: string;
settings: Settings;
}
interface Settings {
generalTab: "profile" | "account" | "security";
}
}
}
type Tab = Backend.Models.User["settings"]["generalTab"];
export function readUser(text: string): JsonResult<Backend.Models.User> {
return __jsonParse<Backend.Models.User>(text, __v0);
}
export function readTab(text: string): JsonResult<Tab> {
return __jsonParse<Tab>(text, __v2);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "id": number; "name": string; "settings": __T1; };
type __T1 = { "generalTab": ("profile") | ("account") | ("security"); };
type __T2 = ("profile") | ("account") | ("security");
function __v1(v: unknown, p: string): __JsonResult<__T1> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j7 = v["generalTab"];
let __j8!: ("profile") | ("account") | ("security");
__j9: {
if (__j7 === "profile") { __j8 = "profile"; break __j9; }
if (__j7 === "account") { __j8 = "account"; break __j9; }
if (__j7 === "security") { __j8 = "security"; break __j9; }
return __jsonFail(p + ".generalTab", "\"profile\" | \"account\" | \"security\"", __j7);
}
const out: { "generalTab": ("profile") | ("account") | ("security"); } = { "generalTab": __j8 };
return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["id"];
if (typeof __j1 !== "number") return __jsonFail(p + ".id", "number", __j1);
const __j2 = __j1;
const __j3 = v["name"];
if (typeof __j3 !== "string") return __jsonFail(p + ".name", "string", __j3);
const __j4 = __j3;
const __j5 = v["settings"];
const __j10 = __v1(__j5, p + ".settings");
if (__jsonIsErr(__j10)) return __j10;
const __j6 = __j10;
const out: { "id": number; "name": string; "settings": __T1; } = { "id": __j2, "name": __j4, "settings": __j6 };
return out;
}
function __v2(v: unknown, p: string): __JsonResult<__T2> {
let out!: ("profile") | ("account") | ("security");
__j11: {
if (v === "profile") { out = "profile"; break __j11; }
if (v === "account") { out = "account"; break __j11; }
if (v === "security") { out = "security"; break __j11; }
return __jsonFail(p, "\"profile\" | \"account\" | \"security\"", v);
}
return out;
}The namespace holds types only, which assert nothing that runs: safe-ts check counts the declare global among the ambient declarations, and no-unchecked-declare reports only values declared there (var config: Config) and members added to a built-in as always there.
A member is found where TypeScript finds it:
- Global namespaces: in
declare global { … }(in a.tsor.d.tsmodule), or at the top of a declaration file without imports or exports (declare namespace Backend.Models { … }). SAFE-TS looks for them in the files under the nearesttsconfig.json: declaration files, and files that saydeclare global. It skipsnode_modules,dist,build,coverage,target,outand hidden directories. - A module's namespace:
export namespace RenderedRoadmap { … }, also next toexport type RenderedRoadmap = …, imported by name (RenderedRoadmap.Area) or withimport * as. - Inside a namespace, a name is first that namespace's member, then the member of the namespaces around it, then a top-level type, also when the namespace goes on in other files (
settings: SettingsinBackend.Models.UserisBackend.Models.Settings).
Interfaces of the same name merge, as in TypeScript. A top-level alias (type User = Backend.Models.User) works, and indexed access into a member does too (Backend.Models.User["settings"]["generalTab"]). An error names the type the way the call wrote it, and where in the declarations the problem is: `parseJson<MergeRequest>`: `Date` (in `Backend.Models.Pipeline.startedAt`) is not supported.
Not found:
- global types from packages (
@types/…, a package'sdeclare global); declare module "…"blocks;- a
.tsfile without imports or exports that declares globals withoutdeclare global.
For those, copy the type into a project file, or wrap it in declare global. The reason: SAFE-TS reads the project's own files, not the packages TypeScript loads, and it finds global declarations with a quick scan instead of building TypeScript's whole program.
Large integers: SafeInt and bigint
JSON has no separate integer type, and JSON.parse silently rounds numbers past 2^53: {"id": 9007199254740993} reads as ...992 (v8.dev).
SafeInt(from@evobug_com/safe-ts-std/json): a number that must be a safe integer. A too-large id is rejected instead of quietly turning into a different id.bigint: sent as a decimal string ("12345678901234567890") and converted withBigInt. Anything else, including a JSON number, is rejected.
✓ Accepted0 diagnostics
ts
import { type JsonResult, parseJson, type SafeInt } from "@evobug_com/safe-ts-std/json";
import { q } from "@evobug_com/safe-ts-std/result";
type Transfer = { readonly id: SafeInt; readonly amount: bigint };
export function transferId(text: string): JsonResult<SafeInt> {
const transfer = q(parseJson<Transfer>(text));
return transfer.id;
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson, type SafeInt } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
type Transfer = { readonly id: SafeInt; readonly amount: bigint };
export function transferId(text: string): JsonResult<SafeInt> {
const __q1 = __jsonParse<Transfer>(text, __v0); if (__q1 instanceof __qErr) return __q1; const transfer = __q1;
return transfer.id;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "id": number; "amount": bigint; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["id"];
if (typeof __j1 !== "number" || !Number.isSafeInteger(__j1)) return __jsonFail(p + ".id", "safe integer", __j1);
const __j2 = __j1;
const __j3 = v["amount"];
if (typeof __j3 !== "string" || !/^-?(0|[1-9][0-9]*)$/.test(__j3)) return __jsonFail(p + ".amount", "integer string (bigint)", __j3);
const __j4 = BigInt(__j3);
const out: { "id": number; "amount": bigint; } = { "id": __j2, "amount": __j4 };
return out;
}Integer ranges: Int<Min, Max>
Int<Min, Max> (from @evobug_com/safe-ts-std/json) is a safe integer from Min to Max, both included: Int<0, 255> is a byte, Int<1, 12> a month. The validator checks the range ($.month: expected integer from 1 to 12, got 13), and arbitrary<T>() only generates values in it, the ends of the range often. To TypeScript it is a number, so write the bounds as integer literals (negative ones too: Int<-12, 14>).
✓ Accepted0 diagnostics
ts
import { type Int, type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { q } from "@evobug_com/safe-ts-std/result";
type Card = { readonly month: Int<1, 12>; readonly year: Int<2000, 2100>; readonly cvc: string };
export function expiry(text: string): JsonResult<string> {
const card = q(parseJson<Card>(text));
return `${card.month}/${card.year}`;
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type Int, type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
type Card = { readonly month: Int<1, 12>; readonly year: Int<2000, 2100>; readonly cvc: string };
export function expiry(text: string): JsonResult<string> {
const __q1 = __jsonParse<Card>(text, __v0); if (__q1 instanceof __qErr) return __q1; const card = __q1;
return `${card.month}/${card.year}`;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "month": number; "year": number; "cvc": string; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["month"];
if (typeof __j1 !== "number" || !Number.isSafeInteger(__j1) || __j1 < 1 || __j1 > 12) return __jsonFail(p + ".month", "integer from 1 to 12", __j1);
const __j2 = __j1;
const __j3 = v["year"];
if (typeof __j3 !== "number" || !Number.isSafeInteger(__j3) || __j3 < 2000 || __j3 > 2100) return __jsonFail(p + ".year", "integer from 2000 to 2100", __j3);
const __j4 = __j3;
const __j5 = v["cvc"];
if (typeof __j5 !== "string") return __jsonFail(p + ".cvc", "string", __j5);
const __j6 = __j5;
const out: { "month": number; "year": number; "cvc": string; } = { "month": __j2, "year": __j4, "cvc": __j6 };
return out;
}Any JSON: JsonValue and unknown
For data whose shape you don't know, or a part you want to keep as it is, use JsonValue (from @evobug_com/safe-ts-std/json): a string, number, boolean, undefined (a JSON null), array or plain object of those. It works as a whole document or as one field, and the value is still checked: validate<JsonValue> rejects NaN, functions, a Date and other class instances, and cycles.
unknown is checked the same way, and typed unknown: parseJson<unknown[]>(text) is any JSON array, for code that only counts the items or hands them on.
✓ Accepted0 diagnostics
ts
import { type JsonResult, type JsonValue, parseJson } from "@evobug_com/safe-ts-std/json";
import { q } from "@evobug_com/safe-ts-std/result";
type Webhook = { readonly event: string; readonly data: JsonValue };
export function webhookEvent(text: string): JsonResult<string> {
const hook = q(parseJson<Webhook>(text));
return hook.event;
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, jsonAny as __jsonAny } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, type JsonValue, parseJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
type Webhook = { readonly event: string; readonly data: JsonValue };
export function webhookEvent(text: string): JsonResult<string> {
const __q1 = __jsonParse<Webhook>(text, __v0); if (__q1 instanceof __qErr) return __q1; const hook = __q1;
return hook.event;
}
// ---- generated by safe-ts: JSON validators ----
type __JsonValue = string | number | boolean | undefined | readonly __JsonValue[] | { readonly [key: string]: __JsonValue };
type __T0 = { "event": string; "data": __JsonValue; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["event"];
if (typeof __j1 !== "string") return __jsonFail(p + ".event", "string", __j1);
const __j2 = __j1;
const __j3 = v["data"];
const __j5 = __jsonAny(__j3, p + ".data");
if (__jsonIsErr(__j5)) return __j5;
const __j4 = __j5;
const out: { "event": string; "data": __JsonValue; } = { "event": __j2, "data": __j4 };
return out;
}In an object, a JSON null stays a key whose value is undefined. In an optional field (data?: JsonValue), null means absent, as for every optional field. To keep every null as it is, use RawJson.
Values from constants: typeof FORMAT, typeof Op.Hello
A type can name a const, in the same file, imported, or declared in the function: typeof FORMAT of const FORMAT = "svg" is the literal type "svg" (a primitive literal needs no as const). A table needs as const: typeof Op.Hello is the literal type 1, (typeof Op)[keyof typeof Op] is the union of its values, (typeof KINDS)[number] the union of a tuple's items. A computed key names a member too: { [Op.Name]: string }.
✓ Accepted0 diagnostics
ts
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { q } from "@evobug_com/safe-ts-std/result";
const FORMAT = "svg";
const KINDS = ["product", "service"] as const;
export const Op = { Hello: 1, Ping: 2 } as const;
type Hello = { readonly op: typeof Op.Hello; readonly name: string };
type Packet = { readonly op: (typeof Op)[keyof typeof Op] };
type Listing = { readonly format: typeof FORMAT; readonly kind: (typeof KINDS)[number] };
export function helloName(text: string): JsonResult<string> {
const hello = q(parseJson<Hello>(text));
return hello.name;
}
export function opOf(text: string): JsonResult<number> {
const packet = q(parseJson<Packet>(text));
return packet.op;
}
export function listingKind(text: string): JsonResult<string> {
const listing = q(parseJson<Listing>(text));
return listing.kind;
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
const FORMAT = "svg";
const KINDS = ["product", "service"] as const;
export const Op = { Hello: 1, Ping: 2 } as const;
type Hello = { readonly op: typeof Op.Hello; readonly name: string };
type Packet = { readonly op: (typeof Op)[keyof typeof Op] };
type Listing = { readonly format: typeof FORMAT; readonly kind: (typeof KINDS)[number] };
export function helloName(text: string): JsonResult<string> {
const __q1 = __jsonParse<Hello>(text, __v0); if (__q1 instanceof __qErr) return __q1; const hello = __q1;
return hello.name;
}
export function opOf(text: string): JsonResult<number> {
const __q2 = __jsonParse<Packet>(text, __v1); if (__q2 instanceof __qErr) return __q2; const packet = __q2;
return packet.op;
}
export function listingKind(text: string): JsonResult<string> {
const __q3 = __jsonParse<Listing>(text, __v2); if (__q3 instanceof __qErr) return __q3; const listing = __q3;
return listing.kind;
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "op": 1; "name": string; };
type __T1 = { "op": (1) | (2); };
type __T2 = { "format": "svg"; "kind": ("product") | ("service"); };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["op"];
if (__j1 !== 1) return __jsonFail(p + ".op", "1", __j1);
const __j2 = 1;
const __j3 = v["name"];
if (typeof __j3 !== "string") return __jsonFail(p + ".name", "string", __j3);
const __j4 = __j3;
const out: { "op": 1; "name": string; } = { "op": __j2, "name": __j4 };
return out;
}
function __v1(v: unknown, p: string): __JsonResult<__T1> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j5 = v["op"];
let __j6!: (1) | (2);
__j7: {
if (__j5 === 1) { __j6 = 1; break __j7; }
if (__j5 === 2) { __j6 = 2; break __j7; }
return __jsonFail(p + ".op", "1 | 2", __j5);
}
const out: { "op": (1) | (2); } = { "op": __j6 };
return out;
}
function __v2(v: unknown, p: string): __JsonResult<__T2> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j8 = v["format"];
if (__j8 !== "svg") return __jsonFail(p + ".format", "\"svg\"", __j8);
const __j9 = "svg";
const __j10 = v["kind"];
let __j11!: ("product") | ("service");
__j12: {
if (__j10 === "product") { __j11 = "product"; break __j12; }
if (__j10 === "service") { __j11 = "service"; break __j12; }
return __jsonFail(p + ".kind", "\"product\" | \"service\"", __j10);
}
const out: { "format": "svg"; "kind": ("product") | ("service"); } = { "format": __j9, "kind": __j11 };
return out;
}A table is often built from other constants, and the build reads those too: a computed key that names a constant ([Kind.Move], [Code.Move]; a number is the key "1", as in JavaScript, and T[1] reads it), and a value that names a member of another as const or frozen table, or a const with a literal value, in the same file or imported:
✓ Accepted0 diagnostics
ts
import { fromFields, type JsonError } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
const LIMITS = Object.freeze({ coordinate: 4096, text: 280 });
export const Kind = { Move: "move", Say: "say" } as const;
export const Code = { Move: 1, Say: 2 } as const;
export const PACKETS = {
[Kind.Move]: { code: Code.Move, max: LIMITS.coordinate },
[Kind.Say]: { code: Code.Say, max: LIMITS.text },
} as const;
type Table = typeof PACKETS;
type Say = { readonly kind: typeof Kind.Say; readonly code: Table["say"]["code"]; readonly text: string };
export function say(text: string): Result<Say, JsonError> {
return fromFields<Say>(["kind", "code", "text"], [Kind.Say, PACKETS.say.code, text]);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, jsonUnknownKey as __jsonUnknownKey, fromFieldsWith as __jsonFromFields, jsonDuplicateKey as __jsonDuplicateKey } from "@evobug_com/safe-ts-std/json"; import { fromFields, type JsonError } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
const LIMITS = Object.freeze({ coordinate: 4096, text: 280 });
export const Kind = { Move: "move", Say: "say" } as const;
export const Code = { Move: 1, Say: 2 } as const;
export const PACKETS = {
[Kind.Move]: { code: Code.Move, max: LIMITS.coordinate },
[Kind.Say]: { code: Code.Say, max: LIMITS.text },
} as const;
type Table = typeof PACKETS;
type Say = { readonly kind: typeof Kind.Say; readonly code: Table["say"]["code"]; readonly text: string };
export function say(text: string): Result<Say, JsonError> {
return __jsonFromFields<Say>(["kind", "code", "text"], [Kind.Say, PACKETS.say.code, text], __b0);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "kind": "say"; "code": 2; "text": string; };
function __b0(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<__T0> {
let __j1: unknown = undefined, __j2: unknown = undefined, __j3: unknown = undefined;
if (k.length === 3 && k[0] === "kind" && k[1] === "code" && k[2] === "text") { __j1 = x[0]; __j2 = x[1]; __j3 = x[2]; } else {
const __j5: boolean[] = [];
for (let __j4 = 0; __j4 < k.length; __j4++) {
switch (k[__j4]) {
case "kind": if (__j5[0] === true) return __jsonDuplicateKey(p, "kind"); __j5[0] = true; __j1 = x[__j4]; break;
case "code": if (__j5[1] === true) return __jsonDuplicateKey(p, "code"); __j5[1] = true; __j2 = x[__j4]; break;
case "text": if (__j5[2] === true) return __jsonDuplicateKey(p, "text"); __j5[2] = true; __j3 = x[__j4]; break;
default: return __jsonUnknownKey(p, k[__j4] ?? "");
}
}
}
if (__j1 !== "say") return __jsonFail(p + ".kind", "\"say\"", __j1);
const __j6 = "say";
if (__j2 !== 2) return __jsonFail(p + ".code", "2", __j2);
const __j7 = 2;
if (typeof __j3 !== "string") return __jsonFail(p + ".text", "string", __j3);
const __j8 = __j3;
const out: __T0 = { "kind": __j6, "code": __j7, "text": __j8 };
return out;
}The build reads the values; it doesn't run code. A member computed at runtime ({ B: compute() } as const) is reported, with the reason: a call, an expression (`v${n}`, a + b), a spread (spread in Object.freeze({ ...A, ...B }) instead), an indexed read (X[k]), a computed key that names no constant, or a reference to a const without as const.
Some values keep their literal types without as const, as in TypeScript, and the build reads them too:
Object.freeze(X)of anas constvalue or another suchconstis that value:(typeof STATUSES)[number]ofconst STATUSES = Object.freeze(STATUS_NAMES).Object.freeze({ title: 80, body: 2000 })keeps the literal types of the primitives in it.- A call of a function declared with a return type, at the top level of a project file: the return type, evaluated for the arguments (as below, where the body says its result with
trust<T>, std's counted claim, becauseObject.fromEntriescan't type it; an overload over a loose implementation says the same without being counted, andno-overloadreports it). Aconsttype parameter (<const T extends readonly string[]>) gets the literal types of the argument (["Hello", "Bye"]); a type parameter constrained to primitives gets a number or string literal (0x10); defaults count. So does an object literal made of spreads of such calls: a code table built from append-only name lists.
✓ Accepted0 diagnostics
ts
import { fromFields, type JsonError } from "@evobug_com/safe-ts-std/json";
import { type Result, trust } from "@evobug_com/safe-ts-std/result";
type CodesOf<T extends readonly string[]> = {
readonly [I in keyof T as I extends `${number}` ? T[I] & string : never]: I extends `${infer N extends number}` ? N : never;
};
/** `{ Hello: 0, Bye: 1 }`: each name's code is its index, so a new name is appended. */
export function codesOf<const T extends readonly string[]>(names: T): CodesOf<T> {
// `Object.fromEntries` can't say which keys it makes: each name, its index.
return trust<CodesOf<T>>(Object.freeze(Object.fromEntries(names.map((name, i) => [name, i]))));
}
export const Op = Object.freeze({ ...codesOf(["Hello", "Bye"]) });
type Packet = { readonly op: typeof Op.Hello; readonly name: string } | { readonly op: typeof Op.Bye };
export function bye(): Result<Packet, JsonError> {
return fromFields<Packet>(["op"], [Op.Bye]);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, jsonUnknownKey as __jsonUnknownKey, fromFieldsWith as __jsonFromFields, jsonDuplicateKey as __jsonDuplicateKey } from "@evobug_com/safe-ts-std/json"; import { fromFields, type JsonError } from "@evobug_com/safe-ts-std/json";
import { type Result, trust } from "@evobug_com/safe-ts-std/result";
type CodesOf<T extends readonly string[]> = {
readonly [I in keyof T as I extends `${number}` ? T[I] & string : never]: I extends `${infer N extends number}` ? N : never;
};
/** `{ Hello: 0, Bye: 1 }`: each name's code is its index, so a new name is appended. */
export function codesOf<const T extends readonly string[]>(names: T): CodesOf<T> {
// `Object.fromEntries` can't say which keys it makes: each name, its index.
return trust<CodesOf<T>>(Object.freeze(Object.fromEntries(names.map((name, i) => [name, i]))));
}
export const Op = Object.freeze({ ...codesOf(["Hello", "Bye"]) });
type Packet = { readonly op: typeof Op.Hello; readonly name: string } | { readonly op: typeof Op.Bye };
export function bye(): Result<Packet, JsonError> {
return __jsonFromFields<Packet>(["op"], [Op.Bye], __b0);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = ({ "op": 0; "name": string; }) | ({ "op": 1; });
function __ba0(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<{ "op": 0; "name": string; }> {
let __j3: unknown = undefined, __j4: unknown = undefined;
if (k.length === 2 && k[0] === "op" && k[1] === "name") { __j3 = x[0]; __j4 = x[1]; } else {
const __j6: boolean[] = [];
for (let __j5 = 0; __j5 < k.length; __j5++) {
switch (k[__j5]) {
case "op": if (__j6[0] === true) return __jsonDuplicateKey(p, "op"); __j6[0] = true; __j3 = x[__j5]; break;
case "name": if (__j6[1] === true) return __jsonDuplicateKey(p, "name"); __j6[1] = true; __j4 = x[__j5]; break;
default: return __jsonUnknownKey(p, k[__j5] ?? "");
}
}
}
if (__j3 !== 0) return __jsonFail(p + ".op", "0", __j3);
const __j7 = 0;
if (typeof __j4 !== "string") return __jsonFail(p + ".name", "string", __j4);
const __j8 = __j4;
const out: { "op": 0; "name": string; } = { "op": __j7, "name": __j8 };
return out;
}
function __ba1(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<{ "op": 1; }> {
let __j9: unknown = undefined;
if (k.length === 1 && k[0] === "op") { __j9 = x[0]; } else {
const __j11: boolean[] = [];
for (let __j10 = 0; __j10 < k.length; __j10++) {
switch (k[__j10]) {
case "op": if (__j11[0] === true) return __jsonDuplicateKey(p, "op"); __j11[0] = true; __j9 = x[__j10]; break;
default: return __jsonUnknownKey(p, k[__j10] ?? "");
}
}
}
if (__j9 !== 1) return __jsonFail(p + ".op", "1", __j9);
const __j12 = 1;
const out: { "op": 1; } = { "op": __j12 };
return out;
}
function __b0(k: readonly string[], x: readonly unknown[], p: string): __JsonResult<__T0> {
let __j1: unknown;
if (k[0] === "op") __j1 = x[0]; else { const __j2 = k.indexOf("op"); __j1 = __j2 < 0 ? undefined : x[__j2]; }
switch (__j1) {
case 0: return __ba0(k, x, p);
case 1: return __ba1(k, x, p);
default: return __jsonFail(p + ".op", "0 | 1", __j1);
}
}The checker reads code tables the same way to compare their values: duplicate-code-value reports two names with one code, also in a table built from two lists ({ ...codesOf(a), ...codesOf(b) } starts both at 0) or from a list and a member written by hand.
What the build can't read is reported with the reason: a function without a declared return type or with several overloads, a type parameter TypeScript would widen (T extends string[] given ["a"], which is string[]; make it const), a call inside a function, and nested objects in Object.freeze({ … }), which TypeScript doesn't keep literal either.
Types computed from others: keyof, T[K], utility and mapped types
The build evaluates these on the resolved types, so a type derived from another one doesn't have to be written out again:
keyof Tis the union ofT's field names;T["a"]andT[keyof T]are field types (withundefinedfor an optional field);T[number]is an array's item, or the union of a tuple's items.Partial<T>andRequired<T>make every field optional or required (for a union, each member).Pick<T, K>andOmit<T, K>keep or drop fields of an object type, inT's order.Exclude<T, U>andExtract<T, U>drop or keep the members ofTthat fitU, such as one variant of a tagged union.NonNullable<T>dropsundefined.- Mapped types over string literal keys (
{ [K in Kind]: boolean }), overstring(a dictionary), and overkeyof T({ [K in keyof T]?: T[K] }), which keepsT's optional fields optional unless?or-?says otherwise. Over a type parameter it maps each member of a union, as TypeScript does, soDeepPartial<T>works.
✓ Accepted0 diagnostics
ts
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
type Shape =
| { readonly tag: "circle"; readonly radius: number }
| { readonly tag: "rect"; readonly w: number; readonly h: number };
type Circle = Extract<Shape, { readonly tag: "circle" }>;
type Settings = { readonly volume: number; readonly muted: boolean; readonly theme: "light" | "dark" };
type SettingsPatch = Partial<Omit<Settings, "theme">>;
type Flags = { readonly [K in keyof Settings]: boolean };
export function readCircle(message: unknown): Result<Circle, JsonError> {
return validate<Circle>(message);
}
export function readPatch(message: unknown): Result<SettingsPatch, JsonError> {
return validate<SettingsPatch>(message);
}
export function readFlags(message: unknown): Result<Flags, JsonError> {
return validate<Flags>(message);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
type Shape =
| { readonly tag: "circle"; readonly radius: number }
| { readonly tag: "rect"; readonly w: number; readonly h: number };
type Circle = Extract<Shape, { readonly tag: "circle" }>;
type Settings = { readonly volume: number; readonly muted: boolean; readonly theme: "light" | "dark" };
type SettingsPatch = Partial<Omit<Settings, "theme">>;
type Flags = { readonly [K in keyof Settings]: boolean };
export function readCircle(message: unknown): Result<Circle, JsonError> {
return __jsonValidate<Circle>(message, __v0);
}
export function readPatch(message: unknown): Result<SettingsPatch, JsonError> {
return __jsonValidate<SettingsPatch>(message, __v2);
}
export function readFlags(message: unknown): Result<Flags, JsonError> {
return __jsonValidate<Flags>(message, __v4);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "tag": "circle"; "radius": number; };
type __T2 = { "volume"?: number; "muted"?: boolean; };
type __T4 = { "volume": boolean; "muted": boolean; "theme": boolean; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["tag"];
if (__j1 !== "circle") return __jsonFail(p + ".tag", "\"circle\"", __j1);
const __j2 = "circle";
const __j3 = v["radius"];
if (typeof __j3 !== "number") return __jsonFail(p + ".radius", "number", __j3);
const __j4 = __j3;
const out: { "tag": "circle"; "radius": number; } = { "tag": __j2, "radius": __j4 };
return out;
}
function __v2(v: unknown, p: string): __JsonResult<__T2> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j5 = v["volume"];
let __j6!: (number) | (undefined);
__j7: {
if (typeof __j5 === "number") { __j6 = __j5; break __j7; }
if (__j5 === undefined || __j5 === null) { __j6 = undefined; break __j7; }
return __jsonFail(p + ".volume", "number | nothing", __j5);
}
const __j8 = v["muted"];
let __j9!: (boolean) | (undefined);
__j10: {
if (typeof __j8 === "boolean") { __j9 = __j8; break __j10; }
if (__j8 === undefined || __j8 === null) { __j9 = undefined; break __j10; }
return __jsonFail(p + ".muted", "boolean | nothing", __j8);
}
const out = { } as { "volume"?: number; "muted"?: boolean; };
if (__j6 !== undefined) out["volume"] = __j6;
if (__j9 !== undefined) out["muted"] = __j9;
return out;
}
function __v4(v: unknown, p: string): __JsonResult<__T4> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j11 = v["volume"];
if (typeof __j11 !== "boolean") return __jsonFail(p + ".volume", "boolean", __j11);
const __j12 = __j11;
const __j13 = v["muted"];
if (typeof __j13 !== "boolean") return __jsonFail(p + ".muted", "boolean", __j13);
const __j14 = __j13;
const __j15 = v["theme"];
if (typeof __j15 !== "boolean") return __jsonFail(p + ".theme", "boolean", __j15);
const __j16 = __j15;
const out: { "volume": boolean; "muted": boolean; "theme": boolean; } = { "volume": __j12, "muted": __j14, "theme": __j16 };
return out;
}The few cases where the build can't tell whether a member fits (Exclude<{ a: number }, Record<string, number>>) are reported, and so are Pick / Omit of a union, which TypeScript doesn't distribute: write Omit<A, "k"> | Omit<B, "k">.
Conditional types, infer and key remapping: types derived from a table
A protocol often derives its packet types from one as const table, so the table is the only place a field is listed. The build evaluates the conditional and mapped types on the resolved types, as TypeScript does:
T extends U ? X : Ychecks whetherTfitsU: literals, primitives, unions, object types (structurally, with optional fields), arrays, tuples andnever. Over a type parameter (T extends …) each member of a union is checked on its own and the results joined;[T] extends [U]checks the whole type.infertakes the part it stands for: an array's item (T extends (infer U)[]), a field (T extends { data: infer D }), a tuple's items (T extends [infer A, infer B]), also with a constraint (infer B extends number).T extends objectasks whetherTis an object type (an object, a dictionary, an array or a tuple), soDeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : Tworks as written.asin a mapped type renames keys or drops them:as T[K] extends number ? never : K,as `get${Capitalize<K & string>}`. Template literal types work when every${…}is a literal or a union of literals;Capitalize,Uncapitalize,UppercaseandLowercasework on string literals.- In the
extendsclause, a template literal is a pattern:K extends `${number}`,K extends `id-${infer N extends number}`(the number literal, ornumberwhen the text isn't how JavaScript writes it),`${infer Head}${infer Rest}`(one character, then the rest), as TypeScript matches them. - Over a tuple:
{ [I in keyof T]: … }maps it item by item whenTis a type parameter; withas, the keys are the items' ("0","1", …), and the others every array has (length, the methods) must be left out (as I extends `${number}` ? … : never). Over an array that isn't a tuple (readonly string[]), the sameasleaves every key out, and the type is{}, as in TypeScript.[...T, 0]spreads a tuple,T["length"]is its length, and[...infer R]takes the rest, so the usual tuple-length arithmetic (Add<A, B>) works. A conditional type whose result is another generic type (Tuple<N, [...T, 0]>) may call itself up to 1000 times, as in TypeScript.
✓ Accepted0 diagnostics
ts
import { arbitrary } from "@evobug_com/safe-ts-std/arbitrary";
import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
export const Op = {
Hello: { code: 1, fields: { name: "string", version: "u8" } },
Move: { code: 2, fields: { x: "i16", y: "i16", path: ["u16"] } },
Ping: { code: 3, fields: {} },
} as const;
type OpName = keyof typeof Op;
type Fields<O extends OpName> = (typeof Op)[O]["fields"];
type FieldType<D> = D extends "string"
? string
: D extends "u8" | "u16" | "i16"
? number
: D extends readonly [infer Item]
? FieldType<Item>[]
: never;
type PacketOf<O extends OpName> = { readonly op: O } & {
readonly [K in keyof Fields<O>]: FieldType<Fields<O>[K]>;
};
export type Packet = { [O in OpName]: PacketOf<O> }[OpName];
export function readPacket(message: unknown): Result<Packet, JsonError> {
return validate<Packet>(message);
}
export const packets = arbitrary<Packet>();ts
import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary } from "@evobug_com/safe-ts-std/arbitrary";
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonError, validate } from "@evobug_com/safe-ts-std/json";
import type { Result } from "@evobug_com/safe-ts-std/result";
export const Op = {
Hello: { code: 1, fields: { name: "string", version: "u8" } },
Move: { code: 2, fields: { x: "i16", y: "i16", path: ["u16"] } },
Ping: { code: 3, fields: {} },
} as const;
type OpName = keyof typeof Op;
type Fields<O extends OpName> = (typeof Op)[O]["fields"];
type FieldType<D> = D extends "string"
? string
: D extends "u8" | "u16" | "i16"
? number
: D extends readonly [infer Item]
? FieldType<Item>[]
: never;
type PacketOf<O extends OpName> = { readonly op: O } & {
readonly [K in keyof Fields<O>]: FieldType<Fields<O>[K]>;
};
export type Packet = { [O in OpName]: PacketOf<O> }[OpName];
export function readPacket(message: unknown): Result<Packet, JsonError> {
return __jsonValidate<Packet>(message, __v0);
}
export const packets = __arbitraryWith<Packet>(__g0);
// ---- generated by safe-ts: JSON validators ----
type __T0 = (__T2) | (__T6) | (__T11);
type __T2 = { "op": "Hello"; "name": string; "version": number; };
type __T6 = { "op": "Move"; "x": number; "y": number; "path": __T9; };
type __T9 = (number)[];
type __T11 = { "op": "Ping"; };
function __v2(v: unknown, p: string): __JsonResult<__T2> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["op"];
if (__j1 !== "Hello") return __jsonFail(p + ".op", "\"Hello\"", __j1);
const __j2 = "Hello";
const __j3 = v["name"];
if (typeof __j3 !== "string") return __jsonFail(p + ".name", "string", __j3);
const __j4 = __j3;
const __j5 = v["version"];
if (typeof __j5 !== "number") return __jsonFail(p + ".version", "number", __j5);
const __j6 = __j5;
const out: { "op": "Hello"; "name": string; "version": number; } = { "op": __j2, "name": __j4, "version": __j6 };
return out;
}
function __v9(v: unknown, p: string): __JsonResult<__T9> {
if (!Array.isArray(v)) return __jsonFail(p, "array", v);
const out: (number)[] = [];
for (let __j16 = 0; __j16 < v.length; __j16++) {
const __j17: unknown = v[__j16];
if (typeof __j17 !== "number") return __jsonFail(p + "[" + __j16 + "]", "number", __j17);
const __j18 = __j17;
out.push(__j18);
}
return out;
}
function __v6(v: unknown, p: string): __JsonResult<__T6> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j8 = v["op"];
if (__j8 !== "Move") return __jsonFail(p + ".op", "\"Move\"", __j8);
const __j9 = "Move";
const __j10 = v["x"];
if (typeof __j10 !== "number") return __jsonFail(p + ".x", "number", __j10);
const __j11 = __j10;
const __j12 = v["y"];
if (typeof __j12 !== "number") return __jsonFail(p + ".y", "number", __j12);
const __j13 = __j12;
const __j14 = v["path"];
const __j19 = __v9(__j14, p + ".path");
if (__jsonIsErr(__j19)) return __j19;
const __j15 = __j19;
const out: { "op": "Move"; "x": number; "y": number; "path": __T9; } = { "op": __j9, "x": __j11, "y": __j13, "path": __j15 };
return out;
}
function __v11(v: unknown, p: string): __JsonResult<__T11> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j21 = v["op"];
if (__j21 !== "Ping") return __jsonFail(p + ".op", "\"Ping\"", __j21);
const __j22 = "Ping";
const out: { "op": "Ping"; } = { "op": __j22 };
return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
let out!: (__T2) | (__T6) | (__T11);
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
switch (v["op"]) {
case "Hello": { const __j7 = __v2(v, p); if (__jsonIsErr(__j7)) return __j7; out = __j7; break; }
case "Move": { const __j20 = __v6(v, p); if (__jsonIsErr(__j20)) return __j20; out = __j20; break; }
case "Ping": { const __j23 = __v11(v, p); if (__jsonIsErr(__j23)) return __j23; out = __j23; break; }
default: return __jsonFail(p + ".op", "\"Hello\" | \"Move\" | \"Ping\"", v["op"]);
}
return out;
}
// ---- generated by safe-ts: test-data generators ----
function __g2(s: __ArbSource, d: number): __T2 {
const out: __T2 = { "op": "Hello", "name": __arbString(s), "version": __arbNumber(s) };
return out;
}
function __g9(s: __ArbSource, d: number): __T9 {
return __arbArray(s, d, __arbNumber);
}
function __g6(s: __ArbSource, d: number): __T6 {
const out: __T6 = { "op": "Move", "x": __arbNumber(s), "y": __arbNumber(s), "path": __g9(s, d + 1) };
return out;
}
function __g11(s: __ArbSource, d: number): __T11 {
const out: __T11 = { "op": "Ping" };
return out;
}
function __g0(s: __ArbSource, d: number): __T0 {
switch (__arbPick(s, d, 3)) {
case 0: return __g2(s, d + 1);
case 1: return __g6(s, d + 1);
default: return __g11(s, d + 1);
}
}Packet is the union of one object type per op. Its members all have a field with a literal of their own (op), so the validator picks the member by that field, and a wrong one is reported as $.op: expected "Hello" | "Move" | "Ping". arbitrary<Packet>() generates every op, for round-trip properties of a codec.
What can't be evaluated is reported, with where: an infer inside a union or another generic type, a template literal with string or number in it, an as that gives a non-literal key, and a check the build can't decide, such as whether an object fits a union of objects through a field that is a union itself. A type left as never is reported too (an optional field of type never must be absent). Generic types instantiated more than 50 levels inside each other are reported as probably endless.
Any keys: Record<string, V>
When the keys are data (user names, product ids, translation keys), type the object Record<string, V> or { readonly [key: string]: V }. Every key is kept, and every value is checked against V. Read the result with getOwn (from @evobug_com/safe-ts-std/dict) or Object.entries, as no-object-dictionary asks: prices["constructor"] on a plain object is the inherited Object function, getOwn(prices, "constructor") is undefined unless the JSON has that key.
✓ Accepted0 diagnostics
ts
import { getOwn } from "@evobug_com/safe-ts-std/dict";
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { type Option, q } from "@evobug_com/safe-ts-std/result";
type Catalog = { readonly currency: string; readonly prices: Readonly<Record<string, number>> };
// A product the catalog doesn't list is missing (`undefined`); a broken catalog is an error.
export function priceOf(text: string, product: string): JsonResult<Option<number>> {
const catalog = q(parseJson<Catalog>(text));
return getOwn(catalog.prices, product);
}
export function cheapest(text: string): JsonResult<Option<string>> {
const catalog = q(parseJson<Catalog>(text));
let best: Option<[string, number]>;
for (const [product, price] of Object.entries(catalog.prices)) {
if (best === undefined || price < best[1]) best = [product, price];
}
return best?.[0];
}ts
import { getOwn } from "@evobug_com/safe-ts-std/dict";
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, isJsonPlainObject as __jsonIsPlainObject, jsonKeyPath as __jsonKeyPath } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { type Option, q } from "@evobug_com/safe-ts-std/result";
type Catalog = { readonly currency: string; readonly prices: Readonly<Record<string, number>> };
// A product the catalog doesn't list is missing (`undefined`); a broken catalog is an error.
export function priceOf(text: string, product: string): JsonResult<Option<number>> {
const __q1 = __jsonParse<Catalog>(text, __v0); if (__q1 instanceof __qErr) return __q1; const catalog = __q1;
return getOwn(catalog.prices, product);
}
export function cheapest(text: string): JsonResult<Option<string>> {
const __q2 = __jsonParse<Catalog>(text, __v0); if (__q2 instanceof __qErr) return __q2; const catalog = __q2;
let best: Option<[string, number]>;
for (const [product, price] of Object.entries(catalog.prices)) {
if (best === undefined || price < best[1]) best = [product, price];
}
return best?.[0];
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "currency": string; "prices": { [key: string]: number }; };
function __va0(v: unknown, p: string): __JsonResult<{ [key: string]: number }> {
if (!__jsonIsPlainObject(v)) return __jsonFail(p, "object", v);
const __j8: [string, number][] = [];
for (const __j5 of Object.keys(v)) {
const __j6: unknown = v[__j5];
if (typeof __j6 !== "number") return __jsonFail(__jsonKeyPath(p, __j5), "number", __j6);
const __j7 = __j6;
__j8.push([__j5, __j7]);
}
const out: { [key: string]: number } = Object.fromEntries(__j8);
return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["currency"];
if (typeof __j1 !== "string") return __jsonFail(p + ".currency", "string", __j1);
const __j2 = __j1;
const __j3 = v["prices"];
const __j9 = __va0(__j3, p + ".prices");
if (__jsonIsErr(__j9)) return __j9;
const __j4 = __j9;
const out: { "currency": string; "prices": { [key: string]: number }; } = { "currency": __j2, "prices": __j4 };
return out;
}- Errors name the key:
$.prices.apple: expected number, got "1.20", and$.prices["green apple"]for a key that isn't an identifier. WithallErrors: true, there is one problem per bad value. - The result is a new plain object, built with
Object.fromEntries. A"__proto__"key in the JSON is kept as an ordinary key, holding data; it doesn't change the prototype. - Only plain objects are accepted:
validaterejects aMap, aDateor a class instance (expected object, got Map). nullvalues: forRecord<string, number>,{"a": null}is an error at$.a. Where the value may be absent (Record<string, Option<V>>,Partial<Record<string, V>>), a key whose value isnullis left out, like an optional field, so the result never holdsundefinedvalues. (In aJsonValueobject,nullstays a key with the valueundefined.)unknownKeysdoesn't apply to the dictionary itself, since every key is known. It still applies to objects inside the values.
In a union, a dictionary can stand next to undefined, primitives or an array (Option<Record<string, V>>, Record<string, V> | readonly V[]). Next to another type that accepts objects (an object type, a second dictionary, JsonValue) it is reported: any object fits the dictionary, so the members can't be told apart. Put the dictionary in a field, and tell the members apart by a tag (Enum<...>).
Keeping a JSON null
Everywhere else a JSON null becomes undefined. Some formats give null a meaning of its own: "category": null for "every category" where a missing category is a mistake, a settings file whose canonical hash must not change, a document passed on byte for byte. Two types from @evobug_com/safe-ts-std/json keep it:
JsonNull, in a type: only anullfits it, and the result keeps it. Withcategory: string | JsonNulla missingcategoryis an error ($.category: expected string | null, got nothing); withcategory?: string | JsonNullit is left out; withnote: Option<string> | JsonNullit isundefined. In a dictionary (Record<string, number | JsonNull>) anullvalue keeps its key.RawJson, for a whole document or one field: any JSON exactly asJSON.parsegives it, everynullkept, soJSON.stringifywrites the same text back. LikeJsonValue, it is checked: noNaN, class instances or cycles.
Write the value as jsonNull, the one null SAFE-TS code writes: in data going out ({ category: jsonNull }), and in test data shaped like a legacy file. JSON.stringify of data holding it, or of a type with JsonNull fields, isn't reported. Compare with null to read it: action.category === null (no-null allows a strict comparison with null).
✓ Accepted0 diagnostics
ts
import { jsonNull, type JsonNull, type JsonResult, parseJson, type RawJson } from "@evobug_com/safe-ts-std/json";
import { q } from "@evobug_com/safe-ts-std/result";
// `"category": null` discounts every category; a missing category is refused.
type Discount = { readonly percent: number; readonly category: string | JsonNull };
export function discountedCategories(text: string, all: readonly string[]): JsonResult<readonly string[]> {
const discount = q(parseJson<Discount>(text));
return discount.category === null ? all : [discount.category];
}
export function everyCategory(percent: number): string {
const discount: Discount = { percent, category: jsonNull };
return JSON.stringify(discount);
}
// The settings exactly as sent, `null`s and all, for a hash both ends agree on.
export function sentSettings(text: string): JsonResult<RawJson> {
return parseJson<RawJson>(text);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult, jsonRaw as __jsonRaw } from "@evobug_com/safe-ts-std/json"; import { jsonNull, type JsonNull, type JsonResult, parseJson, type RawJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
// `"category": null` discounts every category; a missing category is refused.
type Discount = { readonly percent: number; readonly category: string | JsonNull };
export function discountedCategories(text: string, all: readonly string[]): JsonResult<readonly string[]> {
const __q1 = __jsonParse<Discount>(text, __v0); if (__q1 instanceof __qErr) return __q1; const discount = __q1;
return discount.category === null ? all : [discount.category];
}
export function everyCategory(percent: number): string {
const discount: Discount = { percent, category: jsonNull };
return JSON.stringify(discount);
}
// The settings exactly as sent, `null`s and all, for a hash both ends agree on.
export function sentSettings(text: string): JsonResult<RawJson> {
return __jsonParse<RawJson>(text, __va0);
}
// ---- generated by safe-ts: JSON validators ----
type __RawJson = string | number | boolean | null | readonly __RawJson[] | { readonly [key: string]: __RawJson };
type __T0 = { "percent": number; "category": (string) | (null); };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["percent"];
if (typeof __j1 !== "number") return __jsonFail(p + ".percent", "number", __j1);
const __j2 = __j1;
const __j3 = v["category"];
let __j4!: (string) | (null);
__j5: {
if (typeof __j3 === "string") { __j4 = __j3; break __j5; }
if (__j3 === null) { __j4 = null; break __j5; }
return __jsonFail(p + ".category", "string | null", __j3);
}
const out: { "percent": number; "category": (string) | (null); } = { "percent": __j2, "category": __j4 };
return out;
}
function __va0(v: unknown, p: string): __JsonResult<__RawJson> {
const __j6 = __jsonRaw(v, p);
if (__jsonIsErr(__j6)) return __j6;
const out = __j6;
return out;
}jsonNull also writes a JSON null in test data shaped like a legacy file:
✓ Accepted0 diagnostics
ts
import { jsonNull, validate } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Profile = { readonly age?: number; readonly tags: readonly string[] };
export function legacyProfileLoads(): boolean {
// An old export wrote `"age": null` for a user who didn't give one.
return !isErr(validate<Profile>({ age: jsonNull, tags: [] }));
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { jsonNull, validate } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Profile = { readonly age?: number; readonly tags: readonly string[] };
export function legacyProfileLoads(): boolean {
// An old export wrote `"age": null` for a user who didn't give one.
return !isErr(__jsonValidate<Profile>({ age: jsonNull, tags: [] }, __v0));
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "age"?: number; "tags": (string)[]; };
function __va0(v: unknown, p: string): __JsonResult<(string)[]> {
if (!Array.isArray(v)) return __jsonFail(p, "array", v);
const out: (string)[] = [];
for (let __j6 = 0; __j6 < v.length; __j6++) {
const __j7: unknown = v[__j6];
if (typeof __j7 !== "string") return __jsonFail(p + "[" + __j6 + "]", "string", __j7);
const __j8 = __j7;
out.push(__j8);
}
return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["age"];
let __j2!: (number) | (undefined);
__j3: {
if (typeof __j1 === "number") { __j2 = __j1; break __j3; }
if (__j1 === undefined || __j1 === null) { __j2 = undefined; break __j3; }
return __jsonFail(p + ".age", "number | nothing", __j1);
}
const __j4 = v["tags"];
const __j9 = __va0(__j4, p + ".tags");
if (__jsonIsErr(__j9)) return __j9;
const __j5 = __j9;
const out = { } as { "age"?: number; "tags": (string)[]; };
if (__j2 !== undefined) out["age"] = __j2;
out["tags"] = __j5;
return out;
}Values from a list that can grow: Open
A status or a type the server sends is a string from a list the server may add to. With a union of literals, "state": "blocked" from a newer server fails the whole response; with string, the code that looks it up gets undefined. Open<K> from @evobug_com/safe-ts-std/open accepts every string and says which ones this build knows: a listed string becomes { tag: "todo", value: "todo" }, any other { tag: "Unknown", value: "blocked" }. A value that isn't a string is still an error.
✓ Accepted0 diagnostics
ts
import { is } from "@evobug_com/safe-ts-std/enum";
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import type { Open } from "@evobug_com/safe-ts-std/open";
import { q } from "@evobug_com/safe-ts-std/result";
type Issue = { readonly title: string; readonly state: Open<"todo" | "done"> };
export function isDone(text: string): JsonResult<boolean> {
const issue = q(parseJson<Issue>(text)); // "state": "blocked" parses, as Unknown
return is(issue.state, "done");
}ts
import { is } from "@evobug_com/safe-ts-std/enum";
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import type { Open } from "@evobug_com/safe-ts-std/open";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
type Issue = { readonly title: string; readonly state: Open<"todo" | "done"> };
export function isDone(text: string): JsonResult<boolean> {
const __q1 = __jsonParse<Issue>(text, __v0); if (__q1 instanceof __qErr) return __q1; const issue = __q1; // "state": "blocked" parses, as Unknown
return ((issue.state)?.tag === "done");
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "title": string; "state": { tag: "done"; value: "done" } | { tag: "todo"; value: "todo" } | { tag: "Unknown"; value: string }; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["title"];
if (typeof __j1 !== "string") return __jsonFail(p + ".title", "string", __j1);
const __j2 = __j1;
const __j3 = v["state"];
if (typeof __j3 !== "string") return __jsonFail(p + ".state", "string", __j3);
const __j4 = ((__j3 === "done" || __j3 === "todo") ? { tag: __j3, value: __j3 } : { tag: "Unknown", value: __j3 }) as { tag: "done"; value: "done" } | { tag: "todo"; value: "todo" } | { tag: "Unknown"; value: string };
const out: { "title": string; "state": { tag: "done"; value: "done" } | { tag: "todo"; value: "todo" } | { tag: "Unknown"; value: string }; } = { "title": __j2, "state": __j4 };
return out;
}match on it needs an Unknown handler, and a table keyed by it needs a fallback (lookup): see Proof types. Each value is a small object with the same two keys. K can't list "Unknown", which is the tag of the values it doesn't list.
What isn't supported
A type that JSON can't produce is reported by json-type, with the reason:
✕ Rejectedjson-type
ts
import { parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
type Event = { readonly name: string; readonly at: Date };
export function eventName(text: string): string {
const event = parseJson<Event>(text);
return isErr(event) ? "invalid" : event.name;
}JSON has no dates. Read the date as a string, and convert it after checking. A brand (Html, SafeUrl, RegexSource, Ascii) is refused the same way: data can't vouch that it was sanitized or checked, so read a string and make the brand from it (safeHref(link)).
✓ Accepted0 diagnostics
ts
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { q } from "@evobug_com/safe-ts-std/result";
type EventJson = { readonly name: string; readonly at: string };
export function eventDate(text: string): JsonResult<Date> {
const event = q(parseJson<EventJson>(text));
return new Date(event.at);
}ts
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { q } from "@evobug_com/safe-ts-std/result";
type EventJson = { readonly name: string; readonly at: string };
export function eventDate(text: string): JsonResult<Date> {
const __q1 = __jsonParse<EventJson>(text, __v0); if (__q1 instanceof __qErr) return __q1; const event = __q1;
return new Date(event.at);
}
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "name": string; "at": string; };
function __v0(v: unknown, p: string): __JsonResult<__T0> {
if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
const __j1 = v["name"];
if (typeof __j1 !== "string") return __jsonFail(p + ".name", "string", __j1);
const __j2 = __j1;
const __j3 = v["at"];
if (typeof __j3 !== "string") return __jsonFail(p + ".at", "string", __j3);
const __j4 = __j3;
const out: { "name": string; "at": string; } = { "name": __j2, "at": __j4 };
return out;
}| Not supported | Write instead |
|---|---|
Date | an ISO string, converted after checking |
Map, Set | an object or an array of pairs; an array |
any | the actual type, unknown or JsonValue |
null | Option<T> or field?: (a JSON null becomes undefined); JsonNull where null means something of its own |
number, symbol or template literal keys (Record<number, V>, [i: number]: V) | string keys (Record<string, V>), converted after checking; an array for keys 0, 1, 2, … |
keys mixing string and literals (Record<string | "a", V>) | Record<string, V> for any key, or only the literals for a fixed set |
listed fields next to an index signature ({ id: string; [key: string]: string }) | the dictionary in a field of its own: { id: string; extra: Record<string, string> } |
| a dictionary in a union with another type that accepts objects | the dictionary in a field, the members told apart by a tag (Enum<...>) |
infer inside a union or a generic type (T extends Box<infer U>), or in an optional field | the resulting type written out |
object outside a conditional type's test | the object type written out, or Record<string, V> |
keyof a dictionary (string | number) | string |
Pick / Omit of a union | Omit<A, "k"> | Omit<B, "k"> |
template literal types with string or number in them (`id-${string}`) | string, or a union of string literals |
methods, functions, Promise, Result | data only; add behaviour in functions |
a class, a TypeScript enum | an object type; Enum<...> or a union of literals |
a type from library code (a package, or any file under a node_modules directory below the project root, also a global one from @types/…), or from a declare module "…" block | a type declared in a project file (a workspace package counts): imported by name, also through a tsconfig.json paths alias, or global in declare global { … } or a declaration file (namespaces) |
To test code that reads or writes this data, arbitrary<T>() generates values of the same types.
Rules in this guide: json-type, no-unchecked-cast, unhandled-failure