Recursive Type Alias Walks JSON Values

Define arbitrary-depth JSON payloads with a recursive type alias and walk them with narrowing, counting leaves and tracking nesting depth in one pass.

TypescriptData Integrity

Code

typescriptsnippet
32 lines
// 递归别名:JSON 值可以嵌套任意深度,引用自身类型
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

function countLeaves(value: JsonValue): number {
  if (value === null) return 1;
  if (Array.isArray(value)) {
    return value.reduce((sum, item) => sum + countLeaves(item), 0);
  }
  if (typeof value === 'object') {
    return Object.values(value).reduce((sum, item) => sum + countLeaves(item), 0);
  }
  return 1; // string / number / boolean 都是叶子
}

function maxDepth(value: JsonValue, depth = 1): number {
  if (Array.isArray(value)) {
    return Math.max(depth, ...value.map((item) => maxDepth(item, depth + 1)));
  }
  if (typeof value === 'object' && value !== null) {
    return Math.max(depth, ...Object.values(value).map((v) => maxDepth(v, depth + 1)));
  }
  return depth;
}

const payload: JsonValue = {
  id: 42,
  tags: ['alpha', 'beta'],
  meta: { nested: { deep: [true, null, 7] } },
};

console.log('leaves:', countLeaves(payload));
console.log('depth:', maxDepth(payload));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

leaves: 6
depth: 5

The recursive alias

JsonValue refers to itself in two arms — JsonValue[] and { [key: string]: JsonValue } — so arbitrary-depth JSON payloads type-check without any. TS permits this because the recursion flows through object/array positions.

One walk, two answers

countLeaves returns 1 at every non-container (null included) and sums over arrays and object values; maxDepth threads a depth parameter down, taking the max across children. The demo payload prints leaves: 8 and depth: 5.

Narrowing drives the recursion

Array.isArray splits the array arm, typeof value === ‘object’ (with the null check already done) splits the object arm, and the remainder are the leaves — each branch matches the union member precisely.

Interactive Tools for This Topic

FAQ

Why must null be checked before the object branch?
typeof null is 'object' in JavaScript, so without the early null check the object arm would try to recurse into it and crash.
How does the alias express arbitrary depth?
Two of its arms reference JsonValue itself (array elements and property values), so nesting of any depth still conforms to the same type.