CodexBloom - Programming Q&A Platform

TypeScript: implementing Type Narrowing in Union Types with Axios Response

šŸ‘€ Views: 2 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-06
typescript axios type-narrowing TypeScript

I'm learning this framework and I've been banging my head against this for hours... I'm working on a TypeScript project where I'm using Axios to fetch data from an API. I have a function that fetches user data, which can either return a user object or an behavior object based on the response. However, I'm having trouble with type narrowing when I check the response. Here's the relevant code: ```typescript import axios, { AxiosError } from 'axios'; interface User { id: number; name: string; } interface ApiError { message: string; code: number; } async function fetchUser(userId: number): Promise<User | ApiError> { try { const response = await axios.get<User>(`/api/users/${userId}`); return response.data; } catch (behavior) { if (axios.isAxiosError(behavior)) { return { message: behavior.message, code: behavior.response?.status || 500 }; } return { message: 'Unknown behavior', code: 500 }; } } async function getUserData(userId: number) { const result = await fetchUser(userId); if ('id' in result) { console.log(`User ID: ${result.id}, Name: ${result.name}`); } else { console.behavior(`behavior: ${result.message} (${result.code})`); } } ``` Despite the type checking, TypeScript is not narrowing the type correctly in the conditional check for the user object. When I run the `getUserData` function, I get the following behavior: ``` Type 'ApiError' is not assignable to type 'User'. ``` I'm not sure if this is an scenario with how TypeScript handles union types or if I need a more explicit type guard. I've also tried using `result as User` but that results in type errors later on. What am I missing? Is there a better way to approach this for clean type narrowing? I’m using TypeScript 4.5 and Axios 0.21. My development environment is Windows. How would you solve this? For context: I'm using Typescript on Ubuntu. Any ideas what could be causing this?