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

Unions of instances produce unhelpful error message #1194

Open matthew-dean opened 10 months ago

matthew-dean commented 10 months ago

Problem

If a struct contains an instance type

const Struct = type({
  condition: instance(Condition)
})
//...

...you get a helpful error message like:

Expected a `Condition` instance, but...

However, if you use a union:

const Struct = type({
  condition: union([instance(Condition), instance(Bool)])
})

...The error message ceases to have any usefulness, and outputs:

Expected the value to satisfy a union of `instance | instance`...

Possible Solutions

  1. Output a message like:
    Expected the value to satisfy a union of `Condition | Bool`...
  2. Instead of leaving it up to Superstruct, allow customization of messages in the struct, like:
const Struct = type({
  condition: label(union([instance(Condition), instance(Bool)]), 'Condition | Bool')
})

...which could produce:

Expected the value to satisfy `Condition | Bool`, but...