0
0
Typescriptprogramming~30 mins

Type-safe API response handling in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Type-safe API response handling
📖 Scenario: You are building a small TypeScript program that fetches user data from an API. You want to make sure the data you get back matches the expected structure so your program is safe and doesn't crash.
🎯 Goal: Create a type-safe way to handle an API response for user data using TypeScript interfaces and type guards.
📋 What You'll Learn
Create an interface for the user data with exact fields
Create a variable to hold a sample API response object
Write a type guard function to check if an object matches the user interface
Use the type guard to safely print the user's name
💡 Why This Matters
🌍 Real World
APIs often return data that might not be exactly what your program expects. Using type-safe checks helps avoid bugs and crashes.
💼 Career
Type-safe API handling is a key skill for frontend and backend developers working with TypeScript to build reliable applications.
Progress0 / 4 steps
1
Define the User interface
Create a TypeScript interface called User with these exact fields: id as a number, name as a string, and email as a string.
Typescript
Need a hint?

Use the interface keyword and define the three fields with their types.

2
Create a sample API response object
Create a constant variable called apiResponse and assign it this exact object: { id: 101, name: "Alice", email: "alice@example.com" }.
Typescript
Need a hint?

Use const to create the variable and assign the exact object.

3
Write a type guard function
Write a function called isUser that takes a parameter obj of type any and returns a boolean. The function should check if obj has id as a number, name as a string, and email as a string. Use this signature: function isUser(obj: any): obj is User.
Typescript
Need a hint?

Check each property with typeof and make sure obj is not null.

4
Use the type guard to print the user's name
Write an if statement that uses isUser(apiResponse) to check the type. Inside the if, write console.log to print exactly User name: followed by the user's name.
Typescript
Need a hint?

Use a template string inside console.log to print the user's name.