[Question] Default in nested objects
Hello,
I hope you’re doing well.
I have a question regarding this code:
import { Type } from '@sinclair/typebox';
import { Create } from '@sinclair/typebox/value';
const schema = Type.Object({
age: Type.Number({
default: 18
}),
nested: Type.Optional(
Type.Object({
ageNested: Type.Number({
default: 18
})
})
)
});
const a = Create(schema); // { age: 18 }
I was expecting Create to return { age: 18, nested: { ageNested: 18 } }, but it seems that defaults in nested objects are not handled.
Is this the intended behavior?
@Necrelox Hi,
This is expected behavior. The sub property nested is Optional, so TypeBox will skip creating the property as it isn't required. TypeBox will only generate the minimum structures necessary to yield a validate-able value.
It is possible to override this behavior by moving the defaults at an Object level.
const schema = Type.Object({
age: Type.Number(),
nested: Type.Optional(
Type.Object({
ageNested: Type.Number()
})
)
}, {
default: { age: 18, nested: { ageNested: 18 } }
})
Hope this helps S
Thank you very much for the explanation! ❤️ I understand better now !
@Necrelox Hi,
Might close out this issue as it seems like the issue here was resolved.
All the best! S
Thank you very much!
Take care !