示例工程 28-events-async-browser-types

28-events-async-browser-types/03-fetch-json/src/main.ts

typescript · 0.9 KB

运行:28 · fetch-json

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

export interface User {
  name: string;
}
 
export function isUser(value: unknown): value is User {
  if (typeof value !== 'object' || value === null) return false;
  return typeof (value as Record<string, unknown>)['name'] === 'string';
}
 
export async function loadName(url: string, init?: RequestInit): Promise<string> {
  const response = await fetch(url, init);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const data: unknown = await response.json();
  if (!isUser(data)) throw new Error('invalid payload');
  return data.name;
}
 
export async function run(log: (msg: string) => void = console.log): Promise<string[]> {
  if (typeof fetch === 'undefined' || typeof location === 'undefined') {
    throw new Error('本示例需要浏览器环境');
  }
  const lines = [await loadName('./data/user.json')];
  for (const line of lines) {
    log(line);
  }
  return lines;
}