CodexBloom - Programming Q&A Platform

TypeScript: Handling Union Types in Function Generics with advanced patterns

πŸ‘€ Views: 13 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
typescript generics union-types TypeScript

I'm learning this framework and I'm working with an scenario while trying to create a generic function that accepts a union type, and the behavior is not what I expected. My goal is to implement a function that takes an array of either strings or numbers and concatenates them into a single string. However, when I try to call the function with an array of mixed types, TypeScript is throwing an behavior. Here’s the code snippet I have: ```typescript function concatArray<T extends string | number>(arr: T[]): string { return arr.join(''); } const mixedArray = ['Hello', 42, 'World']; const result = concatArray(mixedArray); console.log(result); ``` When I run this code, I get the following behavior: ``` Argument of type '(string | number)[]' is not assignable to parameter of type 'string | number[]'. Type '(string | number)[]' is not assignable to type 'string[]'. ``` I tried explicitly casting the mixedArray to a tuple or using a type assertion, but it didn't resolve the scenario. I also looked into the idea of creating a type guard function to handle the union type more gracefully, but I'm not sure how to implement that in this case. Any suggestions on how to adjust my code to handle this situation properly? Am I missing something in the TypeScript type system? I'm using TypeScript version 4.6.3. I'm using Typescript LTS in this project. Is this even possible?