CodexBloom - Programming Q&A Platform

TypeScript: Handling Union Types with Default Parameters in a Function

πŸ‘€ Views: 14 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
typescript union-types default-parameters TypeScript

I'm prototyping a solution and I'm relatively new to this, so bear with me... I'm working on a TypeScript function that takes a union type as a parameter, but I'm running into issues when I try to use default parameters with it. The function is supposed to accept either a string or a number, but when I define a default value, TypeScript raises an behavior. Here's the code snippet I have so far: ```typescript function processValue(value: string | number = "default") { if (typeof value === 'string') { console.log(`String: ${value}`); } else { console.log(`Number: ${value}`); } } ``` When I try to call `processValue()` without arguments, I get the following behavior: ``` Argument of type '"default"' is not assignable to parameter of type 'string | number'. ``` This is unexpected because I thought that the default value would be compatible with the union type. I've also tried defining the default value as `undefined` and then checking for it inside the function, but I'm not sure if that's the best approach. Here’s what that looks like: ```typescript function processValue(value?: string | number) { if (value === undefined) { value = "default"; } if (typeof value === 'string') { console.log(`String: ${value}`); } else { console.log(`Number: ${value}`); } } ``` While this works, I'm concerned about readability and whether this is considered a best practice. Is there a more elegant solution to this question? How do I properly handle default parameters with union types in TypeScript without running into type errors? I’m using TypeScript version 4.5.2 and I’d appreciate any insights or recommendations on this scenario. I'm working on a service that needs to handle this. Any ideas what could be causing this? Any feedback is welcome!