← 中文资源

简体中文版本

带运行时校验的类型化 JSON 请求

用类型谓词与泛型实现 fetchJson,区分 HTTP、JSON 解析与数据形状错误,并注入请求函数让示例无需真实网络。

阅读英文原文

题目

实现 fetchJson(url, validate, request)。request 返回一个包含 ok、status 和 text() 的响应对象。状态码不是 2xx 时抛出 HttpError;正文无法解析为 JSON 时抛出 JsonError(‘INVALID_JSON’);解析成功但类型谓词不通过时抛出 JsonError(‘INVALID_SHAPE’);成功时返回类型为 T 的值。示例用注入的请求函数模拟不同状态码和正文,最终输出 ok:true 与 value,或 ok:false 与错误代码。

解题思路

先检查 response.ok,失败直接抛 HttpError,避免对错误响应做无意义的解析。成功时读取 text,把 JSON.parse 放在 try/catch 中,捕获后抛 INVALID_JSON。随后调用类型谓词 validate,不通过则抛 INVALID_SHAPE。谓词通过后,TypeScript 会把 parsed 收窄为 T,直接返回即可,无需 as 断言。主流程用 try/catch 捕获三类错误,把 HttpError 映射为 HTTP_状态码,把 JsonError 映射为自身 code。

参考实现要点

ResponseLike 只声明用到的字段,既方便注入模拟对象,也避免依赖完整 DOM 类型。HttpError 用 readonly status 保存状态码,JsonError 用字面量联合限制 code 只能是两种值。isUser 先判断是否为非空对象,再用 Record<string, unknown> 逐字段检查,不能直接访问未知对象的属性。示例中的 request 根据 JSON 的 status 计算 ok 字段,text 返回原样正文。

常见错误

用 as User 直接断言解析结果,类型检查通过但运行时可能字段缺失。先解析正文再判断状态码,404 的错误页会被当成数据解析并报 INVALID_JSON。抛出普通 Error 或字符串,调用方无法可靠区分错误类别。谓词只检查 typeof value === ‘object’,没有排除 null,后续取值会抛错。

验证方式

用 tsc –strict 编译,确认成功分支里的 user 被推断为 User,访问不存在的字段会报错。运行四个样例并比对 JSON。补充测试:201 应视为成功;204 的空正文应得到 INVALID_JSON;对象多出额外字段时仍应通过校验。最后确认错误输出只包含 ok 与 error,不泄漏正文内容。

代码示例

declare const input: string;

interface User {
  id: number;
  name: string;
}

interface ResponseLike {
  ok: boolean;
  status: number;
  text(): Promise<string>;
}

class HttpError extends Error {
  constructor(readonly status: number) {
    super(`HTTP ${status}`);
    this.name = 'HttpError';
  }
}

class JsonError extends Error {
  constructor(readonly code: 'INVALID_JSON' | 'INVALID_SHAPE') {
    super(code);
    this.name = 'JsonError';
  }
}

function isUser(value: unknown): value is User {
  if (typeof value !== 'object' || value === null) return false;
  const record = value as Record<string, unknown>;
  return typeof record.id === 'number' && typeof record.name === 'string';
}

async function fetchJson<T>(
  url: string,
  validate: (value: unknown) => value is T,
  request: (url: string) => Promise<ResponseLike>,
): Promise<T> {
  const response = await request(url);
  if (!response.ok) throw new HttpError(response.status);
  const text = await response.text();
  let parsed: unknown;
  try {
    parsed = JSON.parse(text);
  } catch {
    throw new JsonError('INVALID_JSON');
  }
  if (!validate(parsed)) throw new JsonError('INVALID_SHAPE');
  return parsed;
}

interface Spec {
  url: string;
  status: number;
  body: string;
}

const spec = JSON.parse(input) as Spec;

async function main(): Promise<void> {
  const request = async (): Promise<ResponseLike> => ({
    ok: spec.status >= 200 && spec.status < 300,
    status: spec.status,
    text: async () => spec.body,
  });

  try {
    const user = await fetchJson(spec.url, isUser, request);
    console.log(JSON.stringify({ ok: true, value: user }));
  } catch (error) {
    const code =
      error instanceof HttpError
        ? `HTTP_${error.status}`
        : error instanceof JsonError
          ? error.code
          : 'UNKNOWN';
    console.log(JSON.stringify({ ok: false, error: code }));
  }
}

await main();
export {};