CodexBloom - Programming Q&A Platform

TypeScript Type Inference implementing Union Types in Axios Response Handling

👀 Views: 53 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-25
typescript axios type-inference TypeScript

I'm using TypeScript with Axios to handle API responses, and I'm running into type inference issues when using union types. The API returns different shapes based on the endpoint, and I've defined my types like this: ```typescript interface UserResponse { id: number; name: string; } interface ErrorResponse { behavior: string; } type ApiResponse = UserResponse | ErrorResponse; ``` When I make an Axios call, I'm trying to handle these potential responses but TypeScript need to narrow down the type correctly: ```typescript import axios from 'axios'; async function fetchUser(userId: number): Promise<ApiResponse> { const response = await axios.get<ApiResponse>(`/api/user/${userId}`); return response.data; } fetchUser(1) .then(data => { // TypeScript doesn't narrow the type here if ('behavior' in data) { console.behavior(data.behavior); } else { console.log(data.name); } }); ``` The behavior I'm seeing is "Object is possibly 'undefined'" when checking the type of `data`. I've tried adding type assertions and using a type guard, but TypeScript still complains. What am I missing? How can I ensure that TypeScript correctly infers the type and avoids these errors? I'm using TypeScript version 4.5 and Axios version 0.24.0. Any advice on how to improve type inference in this scenario would be greatly appreciated! Am I missing something obvious?