ianstormtaylor / superstruct

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

Allow optional and nullable enums #1114

Closed TomPenguin closed 1 year ago

TomPenguin commented 1 year ago

I'd like to add nullable in this case.

I couldn't find any problems with following:

yarn test

and

const undefinedTestTypeSchema: Describe<undefined> = literal(undefined)

const nullTestTypeSchema: Describe<null> = literal(null)

const optionalTestTypeSchema: Describe<string | undefined> = optional(string())

const partialEnumTypeSchema: Describe<{ foo?: 'bar' | 'baz' }> = object({
  foo: optional(enums(['bar', 'baz'] as const)),
})

const partialAndNullableEnumTypeSchema: Describe<{
  foo?: 'bar' | 'baz' | null
}> = object({
  foo: optional(nullable(enums(['bar', 'baz'] as const))),
})

const nullableEnumTypeSchema: Describe<{
  foo: 'bar' | 'baz' | null
}> = object({
  foo: nullable(enums(['bar', 'baz'] as const)),
})

const optionalUndefinedSchema: Describe<{ foo?: undefined }> = object({
  foo: literal(undefined),
})

const optionalNullSchema: Describe<{ foo?: null }> = object({
  foo: optional(literal(null)),
})
ianstormtaylor commented 1 year ago

Thanks @TomPenguin! Can you add some typings tests to account for the new allowed behavior? (I should have asked for this on that other PR as well.)