CodexBloom - Programming Q&A Platform

TypeScript - guide with Conditional Types Not Inferring Correctly in Union Types

πŸ‘€ Views: 26 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
typescript conditional-types type-inference TypeScript

I've been researching this but I'm collaborating on a project where After trying multiple solutions online, I still can't figure this out... I'm working with a frustrating scenario with TypeScript's conditional types when working with union types. I'm trying to create a function that returns different types based on input but TypeScript isn't inferring the types correctly. Here’s a simplified example of what I have: ```typescript type A = { kind: 'a'; value: string; }; type B = { kind: 'b'; value: number; }; type C = A | B; function processInput(input: C) { if (input.kind === 'a') { // Expected to infer string here return input.value.toUpperCase(); } else { // Expected to infer number here return input.value * 2; } } ``` When I call `processInput({ kind: 'a', value: 'test' });`, everything works fine. However, if I try calling it with a union type like this: ```typescript const inputs: C[] = [ { kind: 'a', value: 'hello' }, { kind: 'b', value: 42 } ]; inputs.forEach(input => processInput(input)); ``` I get a type behavior on the second case stating that `input.value` is potentially of type 'string' and 'number', which seems incorrect. I’ve tried explicitly casting `input` inside the if branches like this: ```typescript if (input.kind === 'a') { const aInput = input as A; return aInput.value.toUpperCase(); } else { const bInput = input as B; return bInput.value * 2; } ``` But this just feels like a workaround rather than a solution. I would expect TypeScript to correctly narrow down the type based on the conditional check. Does anyone have insights into why this type inference is failing? Am I missing a best practice here? This is happening in TypeScript version 4.8.4. Any help would be appreciated! Is there a better approach? This is my first time working with Typescript stable. Thanks, I really appreciate it! Any help would be greatly appreciated! Any suggestions would be helpful. This issue appeared after updating to Typescript stable. Is this even possible?