AzLearn

تمرين إعادة البناء

API Response Union

أعد كتابة تعامل TypeScript مع استجابة API باستخدام discriminated union.

typescript ~14 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
interface UserProfile {
  id: number;
  name: string;
  email: string;
}

type ApiResponse<T> =
  | { ok: true; status: 200; data: T }
  | { ok: false; status: 400 | 404 | 500; error: string };

function renderResponse(response: ApiResponse<UserProfile>): string {
  if (response.ok) {
    return `${response.data.name} <${response.data.email}>`;
  }

  return `Request failed (${response.status}): ${response.error}`;
}

const responses: ApiResponse<UserProfile>[] = [
  {
    ok: true,
    status: 200,
    data: { id: 7, name: "Sara", email: "[email protected]" },
  },
  {
    ok: false,
    status: 404,
    error: "User not found",
  },
];

for (const response of responses) {
  console.log(renderResponse(response));
}
اكتب هنا