ianstormtaylor / superstruct

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

[Feature] Support for `Required` #1178

Open kevcao-certik opened 1 year ago

kevcao-certik commented 1 year ago

As we have support for Typescript's Partial, can we also have support for Required as well?

arturmuller commented 9 months ago

Makes sense to me! Very open to a PR if anyone wants to take this on.

yeoffrey commented 3 months ago

Just some thoughts I had about this feature.

I think in general SuperStruct wants its user to start with the most restrictive validation, and then gradually loosen it with optional and nullable, etc... Adding required here might become quite confusing.

For example, if we require something that is optional, do we just negate it? What about for partial? To me, the below seems quite awkward.

import { number, object, optional, partial, required } from '../../../src'

export const Struct = required(optional(number()))

export const Struct2 = required(
  partial(
    object({
      thing: number(),
    })
  )
)

The other consideration here is that if we do allow this, then we might end up with a huge callback problem. I've already run into it while trying to test my own implementation of this, but essentially under the hood this is going to make a struct which for each check, will make things optional, then make this required, then optional, then required... Unless we can go into the struct itself and have it simplify itself, I'm worried about the performance of this.

So I can't really see the reason for having this when we could just start in the first place with everything required and loosen it up with modifiers.