arktypea
arktype10mo ago
Genshii

Configure errors in a scope

Is it possible to set a expected/actual/etc handler for every type in a scope?

I have something like this:
const foo = type({
  name: "string",
  myKey: "number",
})
const fooArray = foo.array()

const validatedFooArray = fooArray([{ name: "fooName", myKey: "should be a number" }])
if (validatedFooArray instanceof type.errors) {
  console.log(validatedFooArray.summary)
}


The error summary looks as follows: value at [0].myKey must be a number (was a string)

Ultimately what I want to do is tell the user the name of object that had the error (let's just assume the
name
property is always on the object).

So something like: (for object with name 'foo'): value at [0].myKey must be a number (was a string)

I was thinking of doing something like this:

.configure({
  message: (ctx) => {
    // if the path starts with an array index, prepend the message with the name
    if (/^\[\d+\]\.$/.test(ctx.path.stringify())) {
      const name = ctx.data[0].name
      return `(for object with name '${name}': ${ctx.problem}`
    } else {
      return ctx.problem
    }


But I would need to apply that to all types contained within my foo .
Was this page helpful?