🧪 Frontend Lab
交互式前端学习实验室

异步类型

typescript · intermediate · 15 min · Step 1/2

异步类型

// async 函数自动返回 Promise<T>
async function fetchUser(id: number): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
}

// Promise 链
function getUser(id: number): Promise<User> {
  return fetch(`/api/users/${id}`).then(r => r.json());
}

// 泛型 API 响应
interface ApiResponse<T> {
  data: T;
  status: number;
}

async function fetchApi<T>(url: string): Promise<ApiResponse<T>> {
  const res = await fetch(url);
  return res.json();
}

// 使用
const response = await fetchApi<User[]>('/api/users');
console.log(response.data);  // User[]
即使不写返回类型,TS 也能推断 async 函数返回 Promise<...>