Skip to content

Commit

Permalink
Revision 0.32.19 (#805)
Browse files Browse the repository at this point in the history
* Revert Union Conversion Logic

* Version
  • Loading branch information
sinclairzx81 committed Mar 22, 2024
1 parent 8a6018d commit 9e4c67d
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 7 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@sinclair/typebox",
"version": "0.32.18",
"version": "0.32.19",
"description": "Json Schema Type Builder with Static Type Resolution for TypeScript",
"keywords": [
"typescript",
Expand Down
7 changes: 6 additions & 1 deletion src/value/convert/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,12 @@ function FromUndefined(schema: TUndefined, references: TSchema[], value: any): u
return TryConvertUndefined(value)
}
function FromUnion(schema: TUnion, references: TSchema[], value: any): unknown {
return schema.anyOf.reduce((value, schema) => Visit(schema, references, value), value)
for (const subschema of schema.anyOf) {
const converted = Visit(subschema, references, value)
if (!Check(subschema, references, converted)) continue
return converted
}
return value
}
function Visit(schema: TSchema, references: TSchema[], value: any): unknown {
const references_ = IsString(schema.$id) ? [...references, schema] : references
Expand Down
6 changes: 3 additions & 3 deletions test/runtime/value/convert/union.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ describe('value/convert/Union', () => {
Assert.IsEqual(V2, { x: null })
Assert.IsEqual(V3, { x: 'hello' })
})
it('Should convert last variant in ambiguous conversion', () => {
it('Should convert first variant in ambiguous conversion', () => {
const T = Type.Object({
x: Type.Union([Type.Boolean(), Type.Number()]),
})
const V1 = Value.Convert(T, { x: '1' })
Assert.IsEqual(V1, { x: 1 })
Assert.IsEqual(V1, { x: true })
})
// ----------------------------------------------------------------
// https://github.com/sinclairzx81/typebox/issues/787
Expand All @@ -38,6 +38,6 @@ describe('value/convert/Union', () => {
const C = Convert(T, { a: '1', b: '2', c: '3' })
Assert.IsEqual(A, { a: 1, c: 2 })
Assert.IsEqual(B, { b: 1, c: 2 })
Assert.IsEqual(C, { a: 1, b: 2, c: 3 })
Assert.IsEqual(C, { a: 1, b: '2', c: 3 }) // note: matching on first
})
})

0 comments on commit 9e4c67d

Please sign in to comment.