Define a JSON value type in TypeScript
How to define a recursive JSON value type in TypeScript, what it does and doesn't guarantee, how to validate parsed data, and where JSON.stringify behavior differs from the type.
TypeScript does not ship a built-in type for "any valid JSON value." The standard library types JSON.parse as returning any, which switches off type checking for everything that comes out of it. A common fix is to define your own recursive JSON value type. This review covers what that type looks like, when it is the right tool, what it actually guarantees, and where real JSON serialization behaves differently from what the type suggests.
Clarifying what "TypeScript JSON type" can mean
Searches for a TypeScript JSON type usually mean one of three things. The first is the global JSON object's own type, which describes the parse and stringify methods and is already declared in the standard library. The second is a type for a specific JSON document whose shape you know, such as an API response, which you would write as an ordinary interface or type alias. The third, and the subject of this article, is a general type that accepts any value JSON can represent: strings, numbers, booleans, null, arrays and objects, nested to any depth.
The core definition
The type mirrors the JSON grammar directly. Primitives are listed once, and arrays and objects refer back to the full value type, which makes the definition recursive. Current TypeScript versions accept recursive type aliases written this way.
type JsonPrimitive = string | number | boolean | null;
type JsonArray = JsonValue[];
type JsonObject = { [key: string]: JsonValue };
type JsonValue = JsonPrimitive | JsonArray | JsonObject;
If you prefer not to maintain this yourself, some utility type packages, such as type-fest, export equivalent JsonValue, JsonObject, JsonArray and JsonPrimitive types. Check the definitions in the version you install, because details such as readonly modifiers or handling of optional properties can differ from the hand-written version above.
Is a JsonValue type suitable for your use?
Recommendation: use a JsonValue type when your code genuinely handles arbitrary JSON whose shape it does not control, and use a specific interface whenever the shape is known. The main benefit is that the compiler forces you to narrow a value before using it, instead of letting any silently accept every property access. The decisive tradeoff is that the type only exists at compile time; it does not check data coming from the network, files or user input.
- Good fits: generic utilities that clone, diff, store or forward JSON without interpreting it; configuration blobs and metadata fields with open-ended content; caches and message payloads that must stay serializable; function parameters that should reject non-serializable values such as functions or class instances.
- Better served by a specific interface: API responses, database records or settings objects with a known structure, where you want property names and types checked.
- Better served by unknown plus validation: untrusted input at a system boundary, where the honest type before checking is unknown, not JsonValue.
What the type changes, and what it doesn't
A JsonValue annotation changes nothing about the data or the emitted JavaScript. Types are erased during compilation, so the annotation only affects which operations the compiler allows. This matters most around JSON.parse: because it returns any, assigning its result to a JsonValue variable compiles without any check that the content really matches.
const data: JsonValue = JSON.parse(text); // compiles, but nothing was verified
In practice JSON.parse can only produce values that fit JsonValue, so for that specific source the annotation is accurate. The gap appears when values arrive from elsewhere typed as any or unknown, such as objects assembled by other code or deserialized by a library. To get a runtime guarantee, parse or receive the value as unknown and confirm it with a type guard.
function isJsonValue(value: unknown): value is JsonValue {
if (value === null) return true;
if (typeof value === "string" || typeof value === "boolean") return true;
if (typeof value === "number") return Number.isFinite(value);
if (Array.isArray(value)) return value.every(isJsonValue);
if (typeof value === "object") {
const proto = Object.getPrototypeOf(value);
if (proto !== Object.prototype && proto !== null) return false;
return Object.values(value).every(isJsonValue);
}
return false;
}
The prototype check rejects class instances such as Date or Map, which would otherwise pass because they have no enumerable own properties. The finite-number check excludes NaN and Infinity, which the number type allows but JSON cannot represent. The guard recurses without tracking visited objects, so a cyclic object would overflow the call stack; JSON.parse never produces cycles, but hand-built objects can. For known shapes, a schema validation library is usually a better choice than a hand-written guard, because it checks structure rather than only serializability.
Narrowing a JsonValue before use
Once a value is typed as JsonValue, reading a nested field requires narrowing at each level. This is more verbose than working with any, and that verbosity is the point: each step documents an assumption about the data.
function getName(value: JsonValue): string | undefined {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return undefined;
}
const name = value["name"];
return typeof name === "string" ? name : undefined;
}
Note that with an index signature, value["name"] is typed as JsonValue even when the key is absent at runtime, unless the noUncheckedIndexedAccess compiler option is enabled, in which case it includes undefined. Enabling that option makes the type more honest for open-ended objects.
Will values survive serialization and sharing?
For data that already matches JsonValue, a JSON.stringify and JSON.parse round trip preserves structure and values, with the number caveat below. The surprises come from values that TypeScript lets you pass to JSON.stringify, which accepts any, but that do not fit the JSON model. The table summarizes behavior defined by the JSON.stringify specification.
| Value passed to JSON.stringify | Serialized output | Value after JSON.parse |
| Object property set to undefined | Property omitted | Property missing |
| undefined inside an array | null | null |
| NaN, Infinity or -Infinity | null | null |
| Date instance | ISO date string, via its toJSON method | Plain string, not a Date |
| bigint | Throws a TypeError | Not applicable |
| Map or Set | Empty object | Empty object |
| Function-valued property | Property omitted | Property missing |
Numbers carry one more limit: JSON text can contain integers larger than JavaScript can represent exactly, and JSON.parse converts them to standard double-precision numbers, so integers beyond Number.MAX_SAFE_INTEGER can silently change. If you exchange large IDs or monetary amounts with other systems, sending them as strings avoids the issue. Also, when JSON text contains duplicate keys, JSON.parse keeps the last one, so a value that looked one way in a text editor can parse differently.
A common friction point: interfaces and index signatures
Values typed with an interface are often rejected where a JsonObject is expected, even if every property is JSON-compatible. TypeScript gives object type aliases an implicit index signature for this kind of assignability check, but it does not do so for interfaces. Optional properties cause a second failure, because their type includes undefined, which is not a JsonValue.
interface User { name: string; }
type UserAlias = { name: string };
declare const a: User;
declare const b: UserAlias;
const x: JsonObject = a; // error: interface lacks an index signature
const y: JsonObject = b; // OK
Practical workarounds are to declare such shapes as type aliases, to accept a generic parameter constrained to a JSON-compatible shape instead of JsonObject itself, or to convert at the boundary. Exact behavior with optional properties also depends on whether exactOptionalPropertyTypes is enabled, so confirm against your own compiler settings.
A readonly variant
If parsed data should be treated as immutable, a readonly version prevents accidental mutation at the type level. As with the base type, this is a compile-time constraint only; it does not freeze the object at runtime.
type ReadonlyJsonValue =
| JsonPrimitive
| readonly ReadonlyJsonValue[]
| { readonly [key: string]: ReadonlyJsonValue };
Evidence and remaining gaps
The behavior described here follows from the TypeScript type system and the JSON.parse and JSON.stringify definitions in the ECMAScript standard. No benchmarks, editor-specific tests or measurements were available for this review, so it makes no claims about performance or compile-time cost of deeply recursive types. Compiler error messages and some assignability details vary between TypeScript versions and tsconfig options such as strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes; check the snippets against your own setup before relying on them.