Value.Default transforms array to object in specific scenarios
The Value#Default function transforms an array into an object with '0' property in certain cases. Example:
const schema = Type.Composite([
Type.Object({
arrayOfIds: Type.Array(Type.Object({ id: Type.Number() })),
}),
Type.Object({
arrayOfIds: Type.Array(Type.Object({ id: Type.Number() })),
}),
]);
// This call is just an example and not really relevant in this demo as there are no defaults, but I simplified the reproduction example
const result = Value.Default(schema, {
arrayOfIds: [
{
id: 3,
},
],
})!;
console.log(result); // { arrayOfIds: { '0': { id: 3 } } }
const decoded = Value.Decode(schema, result); // Throws because result.arrayOfIds is an object with '0' property now
Is this expected? Thanks in advance!
I have noticed the same behavior in certain cases when using Value#Decode. Possibly this is because of the same reason. If needed, I can set up a minimal reproduction scenario
@sjoerdvanBommel Hi, sorry for the delay in reply.
This functionality should be fixed in TypeBox 1.0
import Type from 'typebox'
import Value from 'typebox/value'
// ------------------------------------------------------------------
// Updated: TypeBox 1.0
//
// Use Type.Evaluate + Type.Intersect instead of Type.Composite
// ------------------------------------------------------------------
const schema = Type.Evaluate(Type.Intersect([
Type.Object({
arrayOfIds: Type.Array(Type.Object({ id: Type.Number() })),
}),
Type.Object({
arrayOfIds: Type.Array(Type.Object({ id: Type.Number() })),
}),
]))
const result = Value.Default(schema, {
arrayOfIds: [{ id: 3 }],
})!
console.log(result) // { arrayOfIds: [ { id: 3 } ] } - Fixed
const decoded = Value.Decode(schema, result); // { arrayOfIds: [ { id: 3 } ] } - Does not throw
Just be mindful that TypeBox is now published to the typebox name on NPM. Also note that the Composite type has been deprecated for Evaluate. The Evaluate type is a much more powerful version of Composite.
Documentation on 1.0 can be found at the link below.
https://sinclairzx81.github.io/typebox/#/
Will close out this issue for now, but if you have any follow up questions, feel free to ping on this thread. All the best S
No further questions, just want to say thank you for this new release, we will definitely benefit from this! 🙏