arktype icon indicating copy to clipboard operation
arktype copied to clipboard

How to get correct literals from 'predicate' error ?

Open 1qh opened this issue 1 year ago • 0 comments

Given a schema that have nested objects, with values having type as literals

import { type } from 'arktype'
import { argv, file } from 'bun'
import { error, log } from 'node:console'
import { exit } from 'node:process'

import schema from './schema'

if (argv.length < 3 || !argv[2]?.length) {
  error('Usage: bun valid.ts  <file.json>')
  exit(1)
}

const input = (await file(argv[2]).json()) as unknown[]

for (const [idx, item] of input.entries()) {
  log('item', idx)
  const errors = schema(item)
  if (errors instanceof type.errors)
    for (const [i, e] of errors.entries()) {
      log(i)
      const { code, data, expected, message, path } = e
      log({ code, data, expected, message, path: path.toJSON() })
      log('='.repeat(123))
    }
}

currently output for each 'predicate' error:

{
  code: "predicate",
  data: "z",
  expected: "\"a\", \"b\" or \"c\"",
  path: [ "path", "to", "key" ],
  message: "path.to.key must be \"a\", \"b\" or \"c\" (was \"z\")",
}

this is because type of this property is: 'a' | 'b' | 'c' how can I get this array of correct values for each 'predicate' error like ['a', 'b', 'c'] ?

(i know i can extract them from the message, but i don't want to do that)

1qh avatar Oct 15 '25 20:10 1qh