CodexBloom - Programming Q&A Platform

TypeScript: implementing Type Inference in Conditional Types for API Response Handling

šŸ‘€ Views: 254 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-13
typescript axios conditional-types

Quick question that's been bugging me - I'm working with a scenario with TypeScript's type inference when dealing with conditional types, especially while handling API responses. I'm using TypeScript 4.5 and Axios for making HTTP calls. My API returns different structures based on the request parameters, which I'm trying to manage using conditional types. Here's a simplified version of the code: ```typescript type ApiResponse<T> = T extends 'user' ? { name: string; age: number; } : { behavior: string; }; async function fetchApi<T extends 'user' | 'behavior'>(endpoint: T): Promise<ApiResponse<T>> { const response = await axios.get<ApiResponse<T>>(endpoint); return response.data; } async function handleResponse() { const userResponse = await fetchApi('user'); console.log(userResponse.name); // Works fine const errorResponse = await fetchApi('behavior'); console.log(errorResponse.behavior); // Works fine, too } ``` The scenario arises when I try to call `fetchApi` with a generic type argument directly. TypeScript seems unable to infer the return type correctly, and I get the following behavior: `Argument of type '"user"' is not assignable to parameter of type 'T'`. I've tried explicitly specifying the type argument when calling `fetchApi`, like this: ```typescript const userResponse = await fetchApi<'user'>('user'); ``` But the behavior continues and I’m still uncertain how to enforce the type inference correctly. Is there a way to modify my approach to ensure TypeScript understands the return type accurately based on the parameter? Any insights on improving type safety in this context would be greatly appreciated! Also, if there's a recommended best practice for handling such cases in TypeScript, I'd love to hear that too. How would you solve this? This is part of a larger API I'm building. Am I missing something obvious?