Skip to content

Conversation

iamramtin
Copy link
Contributor

Description

Fixes union type conversion issue where Value.Parse() unnecessarily converts values to the first matching type in a union, even when the input already matches one of the union types exactly.

Problem

When using unions like Type.Union([Type.String(), Type.Number()]), numeric values were being converted to strings because the conversion logic would coerce to the first compatible type rather than preserving the original when it's already valid.

// Before (broken)
const schema = Type.Union([Type.String(), Type.Number()])
Value.Parse(schema, 42) // Returns "42" (string) instead of 42 (number)

// After (fixed)  
Value.Parse(schema, 42) // Returns 42 (number), which correctly preserves type

Fixes #1281

Modify Value.Convert to check for exact type matches before attempting
conversion in union types. This prevents unnecessary type coercion when
the input value already matches one of the union schema types.

Fixes sinclairzx81#1281

Signed-off-by: Ramtin Mesgari <26694963+iamramtin@users.noreply.github.com>
@sinclairzx81
Copy link
Owner

@iamramtin Hi, thanks for the PR

Hey sorry about the delay getting this PR looked at. I have been extraordinarily busy on other project work of late which has meant I have had to defer PR reviews, sorry about that.

This said, everything looks great here (and this is a nice fix to improve things for order independent unions!). Happy to merge this one in.

Will publish out later today and let you know once published on this thread.
Thanks again!

@sinclairzx81 sinclairzx81 merged commit 97e3154 into sinclairzx81:master Jul 16, 2025
9 checks passed
@sinclairzx81 sinclairzx81 mentioned this pull request Jul 16, 2025
@sinclairzx81
Copy link
Owner

@iamramtin Hiya,

Updates published on 0.34.38.

Thanks again for the PR, and again, sorry for the delay.
All the best!
S

@iamramtin
Copy link
Contributor Author

Hey @sinclairzx81, all good, thanks for merging this in. I appreciate the work you're doing here with typebox!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Union type conversion issue with Value.Parse()
2 participants