TypeScript: implementing Type Inference in Conditional Types with Union Types
I've searched everywhere and can't find a clear answer. I'm dealing with I can't seem to get I'm trying to configure I'm working on a personal project and I'm learning this framework and Quick question that's been bugging me - I'm working on a TypeScript project (version 4.5) where I need to create a utility type that infers a specific type based on a union type of string literals. I want to check if a string literal is included in a union type, and return either a specific type or a fallback type based on that check. However, I am running into issues with type inference and getting unexpected results. Here’s the utility type I’ve defined: ```typescript type ExtractType<T> = T extends 'foo' ? number : string; ``` When I try to use this utility type on a union type like this: ```typescript type MyUnion = 'foo' | 'bar' | 'baz'; type Result = ExtractType<MyUnion>; ``` I expected `Result` to be a union of types `number | string`, but instead, TypeScript is inferring it as just `string`. I’ve tried using the `infer` keyword like this: ```typescript type Conditional<T> = T extends infer U ? ExtractType<U> : never; ``` But this didn’t produce the result I was looking for either. I also attempted to use mapped types, but I kept getting type errors that `Type 'string' is not assignable to type 'number'.` Here’s the full code snippet I have: ```typescript type ExtractType<T> = T extends 'foo' ? number : string; type MyUnion = 'foo' | 'bar' | 'baz'; type Result = ExtractType<MyUnion>; const example: Result = "hello"; // This line throws an behavior ``` Is there a way to achieve the desired behavior where `Result` correctly represents `number | string`? Any insights on how to improve this or a different approach I should consider would be greatly appreciated! I'm working on a service that needs to handle this. I'd really appreciate any guidance on this. For context: I'm using Typescript on Ubuntu 20.04. Any pointers in the right direction? This is happening in both development and production on Windows 10. What am I doing wrong? My team is using Typescript for this CLI tool. I'm open to any suggestions. Is there a better approach? I'm open to any suggestions.