jquense / yup

Dead simple Object schema validation
MIT License
22.72k stars 924 forks source link

Typing for dynamical objects #2082

Open furstenheim opened 1 year ago

furstenheim commented 1 year ago

This is related to this issue https://github.com/jquense/yup/issues/130. Basically, I would like to describe in yup the "additionalProperties" in a json schema.

Say:

{
    type: 'object',
    additionalProperties: {
        type: 'object',
        properties: {
            a: {
                type: 'string'
            },
            b: {
                type: 'string'
            }
        }
    }
}

I understand the proposed solution using lazy

const schema = lazy(obj => object(
    mapValues(obj, () => object({
        a: string(),
        b: number()
    }))
))

However, when I do InferType<typeof schema>, I get unknown (which is expected).

I would like to get something like:

{[key in string]: {a: string, b: number}}

Help Others Reproduce

Write a runnable test case using the code sandbox template: https://codesandbox.io/s/yup-test-case-gg1g1

NOTE: if you do not provide a runnable reproduction the chances of getting feedback are significantly lower

jquense commented 1 year ago

what does additionalProperties mean here, that the schema might have those properties?

furstenheim commented 1 year ago

Additional properties validates everything that is not covered by properties (and patternProperties, but those I've never had to use)

https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

It is a validator on those properties. If it said "additionalProperties": false it would mean that there is no other property beyond he described ones (as false never succeeds as a json schema).

In this case, it adds a condition to any other property.

Eigilak commented 10 months ago

Having the same issues :I

DSoliz commented 2 weeks ago

I am also in need of this functionality, here is a good api that zod uses record schema. It would be nice to have an equivalent in yup so that types can be restored for this use case.