rescript-schema icon indicating copy to clipboard operation
rescript-schema copied to clipboard

parseOrThrow throws TypeError instead of validation error for `array<option<_>>` inside object

Open tdfairbrother opened this issue 1 year ago β€’ 2 comments

Hi, thanks for this library β€” it's been great to work with! I’ve run into a bug when validating an object that includes a field of type array<option<string>>.

When the JSON input does not include the expected field (e.g. missing foobar), instead of getting a validation error, parseOrThrow crashes with:

TypeError: Cannot read properties of undefined (reading 'length')
at eval (eval at internalCompile (.../node_modules/sury/src/Sury.res.js:927:10), <anonymous>:3:83)
at Object.parseOrThrow (.../node_modules/sury/src/Sury.res.js:1027:32)

πŸ’₯ Expected A SuryError indicating that the field foobar is missing or invalid

πŸ” Reproduction

type t = {foobar: array<option<string>>}

let testSchema = S.schema(s => {
  foobar: s.matches(S.array(S.option(S.string))),
})

let json = (%raw(`{"weird": true}`): Js.Json.t)
Js.log(json->S.parseOrThrow(testSchema))

βœ… Other working cases These similar cases return expected SuryError eg. Failed parsing at ["foobar"]: Expected string[], received undefined

Object with array of string type t = {foobar: array} let testSchema = S.schema(s => { foobar: s.matches(S.array(S.string)), })
Object with optional string type t = {foobar: option} let testSchema = S.schema(s => { foobar: s.matches(S.option(S.string)), })
Top-level array of option type t = array> let testSchema = S.array(S.option(S.string))

It looks like the issue specifically arises when:

  • a field is an array of optional values, and
  • that field is defined inside an object schema, and
  • the input is missing or doesn't match the expected structure.

πŸ” Additional context

I realise that an array<option<_>> is not something that maps to JSON β€” but I'm using it for GraphQL types, where a field might be [String] (nullable elements). I'm using your sury-ppx to decorate those types with @s.nullable option.

Here’s another similar schema that also throws the same error:

type t = {foobar: array<Js.Nullable.t<string>>}

let testSchema = S.schema(s => {
  foobar: s.matches(S.array(S.nullable(S.string))),
})

let json = (%raw(`{"weird": true}`): Js.Json.t)
Js.log(json->S.parseOrThrow(testSchema))

Let me know if you'd like a minimal reproduction repo or failing test β€” happy to help further.

Thanks again! πŸ™Œ

tdfairbrother avatar Jun 05 '25 05:06 tdfairbrother

Thanks for reporting πŸ‘ This is a critical issue my tests missed. I'm going to release a fix as 10.0.2 in a few minutes.

DZakh avatar Jun 05 '25 06:06 DZakh

This is fantastic. I appreciate it β€” thank you!

tdfairbrother avatar Jun 05 '25 06:06 tdfairbrother