-
Notifications
You must be signed in to change notification settings - Fork 148
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Value.Default doesn't work for complex objects #714
Comments
@StevenStavrakis Hi,
Yes, this is by design. As you mentioned, you will need to apply a The current top down approach is written for performance and to avoid reverse traversal through the schematics, it's also written to be "unsurprising" in terms of how things work. Unfortunately, this does come with some verbosity which is largely unavoidable. With this said, if you use const T = Type.Object({
x: Type.Object({
y: Type.Object({
z: Type.Object({
foo: Type.String({ default: 'foo' })
}, { default: {} })
}, { default: {} })
}, { default: {} })
}, { default: {} })
const D = Value.Default(T, undefined) // const D = {
// "x": {
// "y": {
// "z": {
// "foo": "foo"
// }
// }
// }
// } Because import { TypeGuard } from '@sinclair/typebox'
// Recursively Apply Default Annotations to Objects only.
export function DeepDefault<T extends TSchema>(schema: T): T {
if (!TypeGuard.IsObject(schema)) return schema
const properties = Object.keys(schema.properties).reduce((acc, key) => {
return ({ ...acc, [key]: DeepDefault(schema.properties[key]) })
}, {})
return { ...schema, properties, default: {} } as T
}
const T = DeepDefault(Type.Object({
x: Type.Object({
y: Type.Object({
z: Type.Object({
foo: Type.String({ default: 'foo' })
})
})
})
}))
const D = Value.Default(T, undefined) // const D = {
// "x": {
// "y": {
// "z": {
// "foo": "foo"
// }
// }
// }
// } I should note, I wouldn't necessarily recommend this (as there is probably a line between expecting users to submit correct values and generating those values for them), but it is possible if this is really something you need to do. Additionally, you can also instance Array types with Hope this helps |
That does help. I've found a way around my issue by composing multiple schemas instead of one complex object. It ended working in my favor, though it's good to know I can use Thanks for the detailed response, much appreciated. |
This may be intentional, but defaulting to nested objects isn't possible.
I understand how this is supposed to work. I imagine that EVERY property needs a default value, but I think that will not be realistic in this case.
The text was updated successfully, but these errors were encountered: