ianstormtaylor / superstruct

A simple and composable way to validate data in JavaScript (and TypeScript).
https://docs.superstructjs.org
MIT License
7.01k stars 224 forks source link

Dynamic context property access #1187

Open andreisaikouski opened 1 year ago

andreisaikouski commented 1 year ago

I am trying to validate a field whose struct depends on another field, as in issue 123.

The docs specify very little on the dynamic utility and no information on the context type

In essence I am trying to do

enum UserType {
    USER = 'USER',
    ADMIN = 'ADMIN',
}

const myUser = object({
    type: enums(Object.value(UserType)),
    // email should be optional for ADMIN type and required for USER type
    email: dynamic( (value, context) =>
         context.type === UserType.USER ? string() : optional(string())
    )
})

This has several issues, mostly because the context is not as used in the referenced issue. Is there any additional documentation or clarity on this?

Intellisense shows: image

Error:

error TS2339: Property 'type' does not exist on type 'Context'.
    c.type === UserType.USER

Superstruct version 1.0.3