Validate JSON Schema in TypeScript
How JSON Schema validation works in TypeScript: what it checks, when it alters your data, how formatting differs from validation, and which approach to choose.
TypeScript checks your code, not your data. Once a program compiles, its type annotations are erased, so a response body, config file or form payload typed as a User interface can still arrive with a missing field or a string where a number belongs. A JSON Schema validator closes that gap. It checks values at runtime against a declarative schema, and in TypeScript it can also narrow an unknown value to a known type. This review covers what that process changes in your data and what it leaves alone, how readable its output is, and when a lighter approach is enough.
Is schema validation the right fit for your use?
Recommendation: use a JSON Schema validator when data crosses a trust boundary. Examples include API requests and responses, user-supplied files, message queues and configuration loaded at startup. It is also the right choice when the schema has to be shared with other languages or tools. The main benefit is one portable contract that can both reject bad input at runtime and inform your static types. The decisive tradeoff is that you maintain the schema and the TypeScript type side by side, unless you derive one from the other, and you take on a runtime dependency.
Plain TypeScript types with no runtime check are preferable when the data never leaves your own typed code, such as values built and consumed inside one module. If you only need to check that a string is syntactically valid JSON, JSON.parse inside a try/catch is enough. If you only need the JSON to look tidy, use a formatter. Formatting and validation are separate jobs, even though many tools bundle them.
Common ways to do it in TypeScript
| Approach | Source of truth | Runtime validation | Static type |
| Ajv with JSONSchemaType<T> | A TypeScript interface plus a hand-written schema checked against it | Yes, schemas compiled to validator functions | The interface you wrote; the compiler flags schema/interface mismatches |
| TypeBox | Schema built in code with a builder API | Yes, via its own compiler or by passing the output to Ajv | Inferred from the schema with Static<typeof schema> |
| Zod | Zod schema (not JSON Schema natively) | Yes, Zod's own parser | Inferred with z.infer; recent releases can export JSON Schema |
| json-schema-to-typescript | An existing .json schema file | No; generates types only, pair with a validator | Generated interfaces committed or built into the project |
If the schema already exists, for example from an OpenAPI document or another team, generating types from it and validating with Ajv keeps the schema authoritative. If you are starting fresh and your consumers are mostly TypeScript, a schema-first library such as TypeBox avoids writing the shape twice. Zod suits teams that prefer its API and only occasionally need JSON Schema output. Check that its export covers the schema features you depend on. No benchmark or compatibility testing was available for this review, so performance and feature coverage should be confirmed against each library's current documentation.
A minimal Ajv example
import Ajv, { JSONSchemaType } from "ajv";
interface User {
id: number;
email: string;
nickname?: string;
}
const schema: JSONSchemaType<User> = {
type: "object",
properties: {
id: { type: "integer" },
email: { type: "string" },
nickname: { type: "string", nullable: true },
},
required: ["id", "email"],
additionalProperties: false,
};
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);
export function parseUser(raw: string): User {
const data: unknown = JSON.parse(raw);
if (!validate(data)) {
throw new Error(ajv.errorsText(validate.errors));
}
return data; // narrowed to User by the type guard
}
Three details matter here. JSONSchemaType makes the compiler reject a schema that drifts from the interface. In Ajv this requires optional properties to be marked nullable: true. The compiled function is a type guard, so a successful call narrows unknown to User without a cast. Compile each schema once and reuse the function, rather than compiling inside a request handler. Format keywords such as "email" or "date-time" are not checked by core Ajv v8 unless you add the separate ajv-formats package. Ajv v8 also uses separate entry points for newer drafts, Ajv2019 and Ajv2020. Make sure the class you import matches the draft your schema declares.
What does validation actually change?
By default, nothing. A validator reads the value and returns true or false plus a list of errors. The stored data is not reordered, reformatted or rewritten. That default can change, though. Several Ajv options mutate the object being validated:
- useDefaults: fills in missing properties from schema default values.
- coerceTypes: converts values to the schema type, so a string "42" can become the number 42 when the schema expects an integer.
- removeAdditional: deletes properties not listed in the schema instead of rejecting them.
These options are useful for query strings and form data, where everything arrives as text. But they mean the object you log afterwards is no longer the object you received. If you need the original for auditing or error reports, clone it before validating, or keep these options off and handle conversion explicitly.
Parsing and pretty-printing, the formatting half of most JSON tools, can also change data in ways that are easy to miss. Parsing the text and re-serializing it with JSON.stringify(value, null, 2) changes whitespace, but the round trip has other effects too:
- Duplicate keys collapse: JSON.parse keeps the last value, so the earlier one disappears silently.
- Key order can shift: JavaScript objects list integer-like keys first in ascending order, so {"b":1,"2":0,"1":0} re-serializes with "1" and "2" ahead of "b".
- Numeric precision can be lost: integers beyond Number.MAX_SAFE_INTEGER, such as large IDs, are rounded when parsed into JavaScript numbers.
- Number spelling is normalized: 1.0 becomes 1 and 1e2 becomes 100. The value is equal, but the text is not.
A schema validator works on the parsed value, so it cannot detect any of these. A duplicate key or an already-rounded ID passes validation if the surviving value fits the schema. If exact text fidelity matters, use a parser that preserves the source text or represents large numbers as strings in your contract.
Unicode inside validated strings
JSON Schema measures string length in characters as defined by the JSON specification, meaning Unicode code points, not UTF-16 units and not visible symbols. Ajv counts code points by default. A single emoji built from several code points, such as a family emoji joined with zero-width joiners or a flag made of two regional indicators, therefore counts as more than one character toward maxLength. The same is true of a letter followed by a combining accent. If a limit is meant to reflect what users see, document that the schema counts code points, or enforce a separate grapheme-based check in application code.
Stylized "fancy font" text, such as bold or script letters produced by substituting Unicode mathematical alphanumeric symbols, still satisfies type: "string". It will fail a pattern that expects ASCII letters, though, and it is not equal to the plain word it resembles. Lookalike characters in property names are a sharper problem. A key spelled with a Cyrillic letter that looks like a Latin one is a different key, so a required check reports the real key as missing. With additionalProperties: false, the lookalike key is also reported as extra. Both errors are correct, but they can be confusing when the two keys look identical on screen.
Will the output stay readable and usable when shared?
Pretty-printed JSON is plain text, so it survives copy and paste and stays editable. It is also valid input for the same validator. Indentation changes nothing a parser cares about. Minified and formatted versions of the same document parse to the same value, apart from the round-trip effects described above if a tool re-serializes rather than only re-indenting.
Validation errors are less readable by default. Ajv reports each failure with an instancePath in JSON Pointer form, such as /items/3/price, along with the failing keyword and a short message. That is precise for developers and logs, but too terse to show directly to end users. For user-facing messages, map errors to field labels in your own code, or use a companion package designed for custom messages. Turning on allErrors gives a complete list instead of stopping at the first failure. This helps people fixing a file by hand, but it costs extra work on every invalid input, so some APIs leave it off for untrusted traffic.
Accessibility depends on where the output is shown, not on the validator. No documentation or scoped test of how screen readers handle formatted JSON or JSON Pointer paths in a particular editor, terminal or web tool was available for this review. This review therefore makes no claim about any specific assistive technology. Where people relying on assistive technology will read validation results, a plain sentence such as "Item 4: price must be a number" is a safer equivalent than a raw pointer and keyword list.
A caution about online validators
Browser-based JSON formatters and schema validators are convenient for one-off checks. Whether they process data locally or send it to a server cannot be determined from how they look or what they claim on the page. For payloads containing credentials, personal data or internal configuration, validate locally with a library or command-line tool, unless the tool's documented behavior has been verified.
Gaps in this review
No benchmarks, version-specific test results or destination-specific rendering tests were available. The behaviors described are documented library and language behavior, not measured outcomes. Before adopting a library, confirm three things against its current release: the supported schema drafts, the default options, and how its error output appears in the places your team or users will actually read it.