Learn TypeScript Β· 13/14

Asynchronous TypeScript and Error Handling

6 min read

Welcome back, code traveler! πŸš€ Today we are entering the fourth dimension: Time.

In synchronous programming, lines of code execute one after another like polite British citizens queuing for a bus. In asynchronous programming, code executes whenever it feels like itβ€”like cats running around at 3 AM.

JavaScript handles this chaos with Promises and Async/Await. TypeScript doesn't change how JavaScript handles time, but it changes how much anxiety you feel while waiting for the result. It ensures that when your data finally arrives from the server, it actually looks like what you expected, rather than a pile of undefined.

Let's tame the chaos.


1. Typing Promises and Async/Await Functions

The Definition

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.

The Problem

In standard JavaScript, an async function is a bit of a mystery box. You know it returns a Promise, but a Promise of what?

javascript
// JavaScript
async function getUser() {
  return { id: 1, name: "Alice" };
}
// Consumer code:
// Is data a string? A number? An object?
// I have to memorize the function body to know.

The Solution: Promise<T>

TypeScript uses Generics to tell us what is inside the Promise wrapper. If a function returns a string eventually, it returns Promise<string>.

Think of the Promise as a delivery box πŸ“¦. TypeScript forces you to write on the outside of the box exactly what is inside.

Practical Implementation

Basic Async Functions

When you mark a function as async, TypeScript automatically infers that it returns a Promise. However, explicit typing is the industry standard for readability.

typescript
// 1. Explicitly typing the return type
async function fetchGreeting(): Promise<string> {
  return "Hello, World!"; 
  // TS checks: Is this a string? Yes. 
  // It wraps it in a Promise automatically.
}

// 2. What happens if you lie?
async function fetchNumber(): Promise<number> {
  // Error: Type 'string' is not assignable to type 'number'.
  // return "I am not a number"; πŸ”΄
  return 42; // βœ…
}

The "Void" Promise

What if your async function performs an action (like saving a file) but returns nothing? You use Promise<void>.

typescript
async function logToDatabase(message: string): Promise<void> {
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log("Saved:", message);
  // No return statement needed
}

πŸ’‘ Fun Fact

Did you know? Before Promises were standard, we lived in "Callback Hell." Imagine calling a function inside a function inside a function, indenting so far to the right that your code ended up on your colleague's monitor. Promises flattened the pyramid of doom! πŸ“‰


2. Fetching Data: Typing Complex API Responses

The Problem

This is the most common task in modern web development. You call an API (like a weather service or user database). The API sends back a JSON object.
In JavaScript, that JSON is treated as any. You can access response.user.legs.tentacles and JavaScript won't stop you until the code runs and crashes because users (usually) don't have tentacles.

The Solution

We define Interfaces that mirror the structure of the API response, then we tell TypeScript that our fetch request returns that specific shape.

Industry Standard: Interface-Driven Fetching

Let's simulate fetching a User profile.

Step 1: Define the Shape
Always look at your API documentation or the JSON response first.

typescript
// The API returns this JSON:
// {
//   "id": 88,
//   "username": "coder_123",
//   "preferences": {
//     "theme": "dark",
//     "notifications": true
//   }
// }

// We create types to match:
type Theme = "dark" | "light"; // Literal type for extra safety!

interface UserPreferences {
  theme: Theme;
  notifications: boolean;
}

interface UserProfile {
  id: number;
  username: string;
  preferences: UserPreferences; // Nested object
}

Step 2: The Fetch Function
The fetch API in the browser returns a Response object. The .json() method returns Promise<any> by default because TypeScript doesn't know what your backend looks like. We must cast it.

typescript
async function getUserProfile(userId: number): Promise<UserProfile> {
  const response = await fetch(`https://api.example.com/users/${userId}`);
  
  // ⚠️ Crucial Step:
  // .json() returns 'any'. We assign it to our typed variable.
  // In a production app, you might use a validation library like Zod here.
  // For now, we trust the API.
  const data: UserProfile = await response.json();
  
  return data;
}

Step 3: Using the Data
Now, the magic happens. Autocomplete works!

typescript
async function displayUser() {
  const user = await getUserProfile(88);
  
  // TS knows 'user' is UserProfile
  console.log(user.username.toUpperCase()); // βœ…
  
  // TS catches typos immediately:
  // console.log(user.preferencs.theme); 
  // πŸ”΄ Error: Property 'preferencs' does not exist. Did you mean 'preferences'?
}

🧠 Real World Scenario: The "Optional" Trap

APIs are notoriously unreliable. Sometimes a field is missing.
If preferences might be missing, mark it optional (?) in your interface:
preferences?: UserPreferences;

Then TypeScript will force you to check if it exists before using it:
console.log(user.preferences?.theme); (Optional Chaining).


3. Catching Errors: Safely Typing the unknown Error Object

The Definition

A try/catch block allows you to handle code execution failures gracefully without crashing the entire application.

The Problem

In JavaScript, you can throw anything.
throw "I am an error string";
throw 404;
throw new Error("Kaboom");
throw null;

Because of this madness, inside a catch(error) block, TypeScript (since version 4.4) defaults the type of error to unknown.
You cannot simply access error.message because error might be a number or a string.

typescript
try {
  executeRiskyCode();
} catch (error) {
  // πŸ”΄ Error: 'error' is of type 'unknown'.
  console.log(error.message); 
}

The Solution: Type Narrowing

We must check what the error is before treating it like an Error object. This is called Type Narrowing.

Practical Implementation

Pattern 1: The instanceof Check (Recommended)

This is the standard way to handle system errors.

typescript
async function getData() {
  try {
    await fetch("https://broken-api.com");
  } catch (error) {
    // Check: Is this actually an Error object?
    if (error instanceof Error) {
      // Now TS knows 'error' is an Error.
      console.error("Something went wrong:", error.message);
    } else {
      // It was a string, number, or something weird.
      console.error("An unexpected error occurred:", String(error));
    }
  }
}

Pattern 2: Custom Type Guards (Pro Level)

Sometimes you have custom error shapes from an API.

typescript
interface ApiError {
  code: number;
  message: string;
}

// A function that returns true if the error matches our interface
function isApiError(err: unknown): err is ApiError {
  return (
    typeof err === 'object' &&
    err !== null &&
    'code' in err &&
    'message' in err
  );
}

try {
  // ... risky api call
} catch (error) {
  if (isApiError(error)) {
    console.log(`API Error ${error.code}: ${error.message}`);
  } else if (error instanceof Error) {
    console.log("System Error:", error.message);
  }
}

πŸ›‘ Anti-Pattern: The "Any" Cast

Do not do this simply to silence the compiler:
catch (error: any) { ... }
This turns off TypeScript's safety. If you assume it has a .message property and it doesn't, your error handler will throw an error. An error inside an error handler is the inception of programming nightmares.


Summary

  1. Promises: Always return Promise<Type> from async functions. It's the label on the box.
  2. Fetching: Create interfaces that match your JSON. Cast the response.json() result to that interface.
  3. Errors: Errors are unknown. Use instanceof Error to safely access .message.

You have now mastered the art of time travel and disaster management in TypeScript. Go forth and fetch data safely! πŸ“‘


πŸ“š References & Further Reading

Challenge

Challenge: Type-Safe Asynchronous Data Fetching and Error Handling

Your task is to implement a robust, type-safe function fetchUserData that fetches user data from a mock API. This function must correctly type the API's success response, which includes nested objects and optional properties, and also safely handle different types of errors that might be thrown during the process.

Requirements:

  1. Define Interfaces:

    • Create an interface named Post with postId (number) and content (string).
    • Create a nested interface named UserProfile with email (string), lastLogin (Date), and an optional theme property (string).
    • Create a main interface named UserData that includes id (number), username (string), profile (UserProfile), and posts (an array of Post).
    • Create an interface named ApiError for structured API errors, with errorCode (number) and message (string).
  2. Create a Custom Type Guard:

    • Implement a function isApiError(error: unknown): error is ApiError that checks if an unknown value conforms to the ApiError interface. It should return true only if the object has both errorCode and message properties of the correct types.
  3. Implement the Fetch Function:

    • Create an async function named fetchUserData that accepts a userId of type number.
    • Explicitly type the function's return value to be Promise<UserData>.
    • Inside a try...catch block, call the provided mockFetchSuccess(userId) function to simulate a network request.
    • Type the JSON result of the successful response using your UserData interface.
    • Return the typed data.
  4. Implement Type-Safe Error Handling:

    • In the catch block, the error object is unknown.
    • Use your isApiError type guard and the instanceof Error check to narrow the type of the error.
    • Log a specific, user-friendly message to the console for each case:
      • If it's an ApiError, log: API Error [CODE]: MESSAGE (e.g., API Error 404: User not found).
      • If it's a standard Error, log its message property.
      • For any other type of error, log: An unexpected error occurred.
    • The function should not return anything in the catch block, but it must handle these errors gracefully without crashing.

Expected result

Your final code should correctly define all the required interfaces, a custom type guard, and the main asynchronous function with robust, type-safe error handling logic inside the catch block.

typescript
// 1. DEFINE YOUR INTERFACES HERE
interface Post {
  postId: number;
  content: string;
}

interface UserProfile {
  email: string;
  lastLogin: Date;
  theme?: string; // Optional property
}

interface UserData {
  id: number;
  username: string;
  profile: UserProfile;
  posts: Post[];
}

interface ApiError {
  errorCode: number;
  message: string;
}

// 2. CREATE YOUR CUSTOM TYPE GUARD HERE
function isApiError(error: unknown): error is ApiError {
  return (
    typeof error === 'object' &&
    error !== null &&
    'errorCode' in error &&
    'message' in error &&
    typeof (error as ApiError).errorCode === 'number' &&
    typeof (error as ApiError).message === 'string'
  );
}

// 3. & 4. IMPLEMENT THE MAIN FUNCTION AND ERROR HANDLING HERE
async function fetchUserData(userId: number): Promise<UserData | void> {
  try {
    const response = await mockFetchSuccess(userId);
    const data: UserData = await response.json();

    // Safely access optional property for demonstration
    console.log(`User theme: ${data.profile.theme?.toUpperCase() ?? 'Not set'}`);
    
    return data;

  } catch (error) {
    if (isApiError(error)) {
      console.error(`API Error ${error.errorCode}: ${error.message}`);
    } else if (error instanceof Error) {
      console.error(`Error: ${error.message}`);
    } else {
      console.error('An unexpected error occurred.');
    }
  }
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.