CodexBloom - Programming Q&A Platform

TypeScript - Type Inference implementing a Function Returning a Promise of Different Types

👀 Views: 27 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-29
typescript promise type-inference TypeScript

I'm migrating some code and I'm working with an scenario with TypeScript where I'm trying to write a function that returns a Promise, but TypeScript isn't inferring the return type correctly... I'm using version 4.5.2, and my function is supposed to return either a string or a number based on the input parameters. Here's an example of my code: ```typescript function fetchData(type: 'string' | 'number'): Promise<string | number> { return new Promise((resolve) => { setTimeout(() => { if (type === 'string') { resolve('Hello World'); } else { resolve(42); } }, 1000); }); } async function logData() { const data = await fetchData('string'); console.log(data.toUpperCase()); // behavior: Property 'toUpperCase' does not exist on type 'string | number' } ``` The behavior I'm getting is `Property 'toUpperCase' does not exist on type 'string | number'`. I thought that since I'm specifying the return type as `Promise<string | number>`, TypeScript should know that `data` is a string when I call `fetchData('string')`. I've tried using type assertions like `const data = await fetchData('string') as string;`, but it feels hacky and I would prefer a cleaner solution. Is there a better way to handle this while keeping my function as flexible as possible? Am I missing something in my type definitions or is there a better approach to type inference in this scenario? This is my first time working with Typescript stable. Any ideas how to fix this? I'm developing on CentOS with Typescript.