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.
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'); } }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Call fetch('/api/user') | Fetch promise starts | Pending response |
| 2 | Await response | Response received | { status: 200, body: JSON } |
| 3 | Parse JSON | Convert response to object | { id: 1, name: 'Alice' } |
| 4 | Type assertion as User | Assume data is User type | data typed as User |
| 5 | Check data.id and data.name | Both exist? | True |
| 6 | Return data | User object returned | { id: 1, name: 'Alice' } |
| Exit | End function | Successful return | User data ready to use |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| res | undefined | { status: 200, body: JSON } | { status: 200, body: JSON } | { status: 200, body: JSON } |
| data | undefined | { id: 1, name: 'Alice' } | typed as User | { id: 1, name: 'Alice' } |
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