CodexBloom - Programming Q&A Platform

TypeScript: How to type a function that processes an array of mixed types in a way that retains type safety?

đź‘€ Views: 29 đź’¬ Answers: 1 đź“… Created: 2025-06-09
typescript type-safety arrays

I'm trying to figure out I'm a bit lost with I keep running into I've searched everywhere and can't find a clear answer. I'm working on a TypeScript function that takes an array of mixed types—specifically, strings and numbers—and processes them in a specific way depending on their type. However, I'm struggling with how to type this function correctly so that it can accept an array containing both types while still maintaining type safety. Here’s my attempt at defining the function: ```typescript function processMixedArray(arr: (string | number)[]): void { arr.forEach(item => { if (typeof item === 'string') { console.log('String:', item.toUpperCase()); } else if (typeof item === 'number') { console.log('Number:', item * 2); } }); } ``` While this works, I noticed that when I try to call this function with a typed array, TypeScript throws an error, which I didn’t expect: ```typescript const mixedArray: (string | number)[] = ['hello', 42, 'world', 100]; processMixedArray(mixedArray); ``` The error I’m seeing is `Argument of type '(string | number)[]' is not assignable to parameter of type '(string | number)[]'.` This seems odd since the types should be compatible. I’ve checked that my TypeScript version is 4.5.2, and I've also verified that my tsconfig is set up correctly with `strict: true` for better type checking. Additionally, I want to ensure that the function handles empty arrays gracefully and returns a value instead of `void`, to make it more versatile. I’d like to return an array of processed results instead. Here’s my updated definition: ```typescript function processMixedArray(arr: (string | number)[]): (string | number)[] { return arr.map(item => { if (typeof item === 'string') { return item.toUpperCase(); } else if (typeof item === 'number') { return item * 2; } return item; // fallback case }); } ``` This change does eliminate the previous error, but now I’m unsure if this approach is idiomatic and efficient in TypeScript. Is there a better way to implement this pattern that ensures both type safety and code clarity? Any tips on how to refine this further or address potential edge cases would be appreciated. Is there a better approach? I'm working with Typescript in a Docker container on Ubuntu 20.04. Any help would be greatly appreciated! The project is a desktop app built with Typescript. Hoping someone can shed some light on this.