fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
5.6k stars 169 forks source link

Property 'key' does not exist on type 'IssuePathItem' #694

Closed zougari47 closed 3 days ago

zougari47 commented 4 days ago

IDE tell me that Property 'key' does not exist on type 'IssuePathItem'.. But when I log it it gives me the expected value.(in this case "message") Here is the snippet

function validate() {
    const schema = v.object({
      name: v.pipe(v.string(), v.nonEmpty('Name is required')),
      email: v.pipe(v.string(), v.trim(), v.email('Invalid Email')),
      message: v.custom(
        input => typeof input === 'string' && input.split(' ').length > 5,
        'Please write a bit more so I can understand you better!'
      ),
    })

    const name = nameInput!.value ?? ''
    const email = emailInput!.value ?? ''
    const message = messageInput!.value ?? ''

    const result = v.safeParse(schema, { name, email, message })

    console.log(result)

    if (!result.success) {
      result.issues.map(issue => {
        console.log(issue.path![0].key) // 'message'
        if (issue.path && issue.path[0].key === 'message') { // here it give me the error for .key
          // show message
        }
      })
    }

    return true
  }
fabian-hiller commented 4 days ago

This is because not every path item has a .key property, but I plan to improve the developer experience on this part by adding key: undefined in this case. There is a workaround to fix the TS error. Here is an example:

if (issue.path && 'key' in issue.path![0] && issue.path![0].key === 'message') {
  // show message
}

Tip: You can also pass the issue to v.getDotPath(issue) to get its path.

fabian-hiller commented 3 days ago

v0.36.0 is available