typebox icon indicating copy to clipboard operation
typebox copied to clipboard

[Question] Default in nested objects

Open Necrelox opened this issue 6 months ago • 2 comments

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 avatar Jun 20 '25 10:06 Necrelox

@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

sinclairzx81 avatar Jun 22 '25 03:06 sinclairzx81

Thank you very much for the explanation! ❤️ I understand better now !

Necrelox avatar Jun 23 '25 12:06 Necrelox

@Necrelox Hi,

Might close out this issue as it seems like the issue here was resolved.

All the best! S

sinclairzx81 avatar Sep 09 '25 15:09 sinclairzx81

Thank you very much!

Take care !

Necrelox avatar Sep 10 '25 07:09 Necrelox