TypeScript class method type narrowing guide with union types and generics
This might be a silly question, but This might be a silly question, but I'm working with a perplexing scenario with TypeScript when trying to use union types and generics in my class method... I have a class that accepts a generic type that can either be a string or a number, and I want to narrow down the type within a method to handle these types differently. However, I'm getting a type behavior when I try to return a specific value based on the type narrowed down by `typeof`. Here's the code snippet: ```typescript class Processor<T extends string | number> { process(input: T): string { if (typeof input === 'string') { return `String received: ${input}`; } else if (typeof input === 'number') { return `Number received: ${input}`; } return 'Invalid input'; // behavior: Type 'string' is not assignable to type 'never'. } } const stringProcessor = new Processor<string>(); const numberProcessor = new Processor<number>(); console.log(stringProcessor.process('Hello')); // Works fine console.log(numberProcessor.process(100)); // Works fine console.log(numberProcessor.process('Hello')); // behavior: Argument of type 'string' is not assignable to parameter of type 'number'. ``` I initially thought that the scenario might be with TypeScript not being able to infer the type correctly, but I verified that the generic types are indeed specified. I also tried modifying the return type of the `process` method to `string | undefined`, but that didn’t resolve the type behavior. How can I properly handle this situation in TypeScript while maintaining type safety? Is there a better approach that I might be overlooking? I'm working on a service that needs to handle this.