← 中文资源

简体中文版本

递归 JSON 值类型

为任意 JSON 定义递归类型,并据此校验 unknown 输入,从而在不使用 any 的情况下安全遍历嵌套结构。

阅读英文原文

实现说明

除了函数 isJson、getIn,文件里再无其他定义。 迭代发生在 for (const key of path) 内部——循环之外的语句只执行一遍。

使用要点

  • 守卫 value === null 命中后立刻用提前的 return 结束这一轮。
  • 值得导入的表面是 isJson;周围的辅助代码对片段是私有的。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 isJson、getIn。

主要签名是 export function isJson(value: unknown)

核心语句

if (type === "string" || type === "number" || type === "boolean") return true;
return Object.values(value as Record<string, unknown>).every(isJson);
if (Array.isArray(value)) return value.every(isJson);

代码示例

export type JsonValue =
  | string
  | number
  | boolean
  | null
  | JsonValue[]
  | { [key: string]: JsonValue };

export function isJson(value: unknown): value is JsonValue {
  if (value === null) return true;
  const type = typeof value;
  if (type === "string" || type === "number" || type === "boolean") return true;
  if (Array.isArray(value)) return value.every(isJson);
  if (type === "object") {
    return Object.values(value as Record<string, unknown>).every(isJson);
  }
  return false;
}

export function getIn(data: JsonValue, path: string[]): JsonValue | undefined {
  let current: JsonValue | undefined = data;
  for (const key of path) {
    if (current === null || typeof current !== "object" || Array.isArray(current)) {
      return undefined;
    }
    current = (current as Record<string, JsonValue>)[key];
  }
  return current;
}