📖 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
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
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
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
Hint
Use a template string inside console.log to print the user's name.
Practice
(1/5)
1. What is the main benefit of using type-safe API response handling in TypeScript?
easy
A. It makes the API faster to respond.
B. It removes the need for testing API responses.
C. It automatically fixes bugs in the API.
D. It helps catch errors early by defining expected data shapes.
Solution
Step 1: Understand type safety purpose
Type-safe handling means defining what data should look like before using it.
Step 2: Identify the benefit
This helps catch mistakes early, like missing or wrong data types, before running the program.
Final Answer:
It helps catch errors early by defining expected data shapes. -> Option D
Quick Check:
Type safety = Early error detection [OK]
Hint: Type safety means catching errors before running code [OK]
Common Mistakes:
Thinking type safety improves API speed
Believing it fixes bugs automatically
Assuming it replaces testing
2. Which TypeScript syntax correctly defines a generic function to fetch API data with a type-safe response?
easy
A. function fetchData(url: string): Promise<any> { /* ... */ }
B. function fetchData<T>(url: string): Promise<T> { /* ... */ }
C. function fetchData<T>(url: string): T { /* ... */ }
D. function fetchData(url: string): T { /* ... */ }
Solution
Step 1: Understand generic function syntax
Generic functions use <T> to represent a type parameter, allowing flexible typing.
Step 2: Check return type for async fetch
Fetching data returns a Promise of type T, so the return type must be Promise<T>.
Final Answer:
function fetchData<T>(url: string): Promise<T> { /* ... */ } -> Option B
A. Missing type assertion or validation for json before returning.
B. The fetch call should not use await.
C. The interface ApiResponse is missing a constructor.
D. The function should return void instead of Promise<ApiResponse>.
Solution
Step 1: Check how json is handled
json is returned directly without confirming it matches ApiResponse shape.
Step 2: Understand type safety requirement
TypeScript needs either a type assertion or runtime validation to ensure json fits ApiResponse.
Final Answer:
Missing type assertion or validation for json before returning. -> Option A
Quick Check:
Validate json shape before return [OK]
Hint: Always validate or assert API response type [OK]
Common Mistakes:
Assuming fetch json is automatically typed
Ignoring need for runtime checks
Misunderstanding async/await usage
5. You want to create a type-safe function that fetches a list of users from an API and returns only users with an active status. Which approach correctly applies type-safe API response handling?
hard
A. Define interface User with 'active' boolean, fetch data as Promise, then filter users by active before returning.
B. Fetch data as Promise<any>, filter users by active without type checking, then cast to User[].
C. Define interface User without 'active', fetch data as Promise, then filter users by active.
D. Fetch data as Promise, return data without filtering to keep type safety.
Solution
Step 1: Define User interface including 'active' property
To filter by active status, the User type must include an 'active' boolean field.
Step 2: Fetch data as Promise<User[]> and filter
Fetching with correct type ensures type safety; filtering users by active keeps the result accurate and typed.
Final Answer:
Define interface User with 'active' boolean, fetch data as Promise<User[]>, then filter users by active before returning. -> Option A
Quick Check:
Correct interface + typed fetch + filter = Define interface User with 'active' boolean, fetch data as Promise, then filter users by active before returning. [OK]
Hint: Include all needed fields in interface before filtering [OK]
Common Mistakes:
Casting any to User[] without checks
Filtering on missing properties in interface
Returning unfiltered data losing requirements
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.