0
0
Typescriptprogramming~10 mins

Type-safe API response handling in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Type-safe API response handling
Start API call
Fetch response
Parse JSON
Validate type
Use data
End
This flow shows how an API call is made, the response is parsed, then checked for correct type before using or handling errors.
Execution Sample
Typescript
async function fetchUser() {
  const res = await fetch('/api/user');
  const data = await res.json() as User;
  if (data && data.id && data.name) {
    return data;
  } else {
    throw new Error('Invalid data');
  }
}
This code fetches user data from an API, asserts its type, and checks required fields before returning or throwing an error.
Execution Table
StepActionEvaluationResult
1Call fetch('/api/user')Fetch promise startsPending response
2Await responseResponse received{ status: 200, body: JSON }
3Parse JSONConvert response to object{ id: 1, name: 'Alice' }
4Type assertion as UserAssume data is User typedata typed as User
5Check data.id and data.nameBoth exist?True
6Return dataUser object returned{ id: 1, name: 'Alice' }
ExitEnd functionSuccessful returnUser data ready to use
💡 Function ends after returning valid user data or throwing error if invalid
Variable Tracker
VariableStartAfter Step 3After Step 4Final
resundefined{ status: 200, body: JSON }{ status: 200, body: JSON }{ status: 200, body: JSON }
dataundefined{ id: 1, name: 'Alice' }typed as User{ id: 1, name: 'Alice' }
Key Moments - 2 Insights
Why do we check data.id and data.name after asserting the type?
Because 'as User' only tells TypeScript to treat data as User but does not verify the actual content at runtime. The check ensures the data really has required fields (see step 5 in execution_table).
What happens if the API returns data missing 'name'?
The condition in step 5 fails, so the function throws an error instead of returning invalid data, preventing bugs later.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'data' after step 3?
Aundefined
B{ id: 1, name: 'Alice' }
CFetch promise
DError thrown
💡 Hint
Check the 'Evaluation' and 'Result' columns at step 3 in execution_table.
At which step does the code verify the data has required fields?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look for the condition check in execution_table rows.
If the API returned { id: 2 } without 'name', what would happen?
AError thrown at step 5
BType assertion fails at step 4
CData returned successfully
DFetch fails at step 1
💡 Hint
Refer to key_moments about missing fields and step 5 condition.
Concept Snapshot
Type-safe API response handling:
- Fetch data with fetch()
- Parse JSON with res.json()
- Use 'as Type' to assert type
- Check required fields at runtime
- Return data if valid, else throw error
Ensures safe use of API data in TypeScript
Full Transcript
This example shows how to safely handle API responses in TypeScript. First, we call fetch to get data from the server. Then we parse the response as JSON. We tell TypeScript to treat the data as a specific type using 'as User'. However, this does not check the data's actual shape, so we manually verify required fields like 'id' and 'name'. If the data is valid, we return it. Otherwise, we throw an error to avoid using bad data. This approach helps prevent bugs by combining type assertions with runtime checks.