Skip to content

How to get correct literals from 'predicate' error ? #1518

@1qh

Description

@1qh

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    To do

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions