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
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.
// 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>.
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.
// 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.
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!
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.
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.
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.
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
- Promises: Always return
Promise<Type>from async functions. It's the label on the box. - Fetching: Create interfaces that match your JSON. Cast the
response.json()result to that interface. - Errors: Errors are
unknown. Useinstanceof Errorto 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:
Define Interfaces:
- Create an interface named
PostwithpostId(number) andcontent(string). - Create a nested interface named
UserProfilewithemail(string),lastLogin(Date), and an optionalthemeproperty (string). - Create a main interface named
UserDatathat includesid(number),username(string),profile(UserProfile), andposts(an array ofPost). - Create an interface named
ApiErrorfor structured API errors, witherrorCode(number) andmessage(string).
- Create an interface named
Create a Custom Type Guard:
- Implement a function
isApiError(error: unknown): error is ApiErrorthat checks if anunknownvalue conforms to theApiErrorinterface. It should returntrueonly if the object has botherrorCodeandmessageproperties of the correct types.
- Implement a function
Implement the Fetch Function:
- Create an
asyncfunction namedfetchUserDatathat accepts auserIdof typenumber. - Explicitly type the function's return value to be
Promise<UserData>. - Inside a
try...catchblock, call the providedmockFetchSuccess(userId)function to simulate a network request. - Type the JSON result of the successful response using your
UserDatainterface. - Return the typed data.
- Create an
Implement Type-Safe Error Handling:
- In the
catchblock, theerrorobject isunknown. - Use your
isApiErrortype guard and theinstanceof Errorcheck to narrow the type of theerror. - 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 itsmessageproperty. - For any other type of error, log:
An unexpected error occurred.
- If it's an
- The function should not return anything in the catch block, but it must handle these errors gracefully without crashing.
- In the
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.
// 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.');
}
}
}