Skip to content

Accessing errormessages on FieldArray  #4915

Open
@AstraRitter

Description

@AstraRitter

What happened?

This is my first Github issue, so please bear with me...

The keys in the Error object don't match their TS definition. Lets say I have the Following:

<script setup lang="ts">
import { useFieldArray, useForm } from 'vee-validate'
import { array, object, string } from 'yup'

interface PhoneNumber {
   phone: string
   type: string
}

const { errors, handleSubmit } = useForm<{
  phoneNumbers: PhoneNumber[]
}>({
  initialValues: {
    phoneNumbers: [{phone: '1234567', type: 'private-landline'}, {phone: '9', type: 'private-mobile'}],
  },
  validationSchema: object({
    phoneNumbers: array().of(
      object({
        phone: string().required().min(4, 'at least 4 digits'),
        type: string()
      }),
    ),
  }),
})

const { fields } = useFieldArray<PhoneNumber>('phoneNumbers')

const onSubmit = handleSubmit(
  (values) => {
    console.debug(values)
  },
  (form) => {
    console.debug('failed', form.errors)
  },
)
</script>

and in the markup:

<template>
  <div
    v-for="(entry, idx) in fields"
    :key="entry.key"
  >
    <FormSelect
      v-model:selected="entry.value.type"
      :name="`phoneNumbers.${idx}.type`" 
      :options="[phoneTypeOptions]"
      @blur="onSubmit"
    />
    <TextInput
      v-model="entry.value.phone"
      :error-message="errors[`phoneNumbers[${idx}].phone`]" // => ts-error
      :name="`phoneNumbers.${idx}.phone`"
      @blur="onSubmit"
    />
  </div>
</template>

Although the code is working I get the following TS-error:

Element implicitly has an 'any' type because expression of type 'phoneNumbers[${number}].phone' can't be used to index type 'Partial<Record<"phoneNumbers" | phoneNumbers.${number} | phoneNumbers.${number}.phone | ....

But when I console.log the errors-object I get:

{
  phonenumbers[1].phone: 'at least 4 digits'
}

When I write the code according to type definitions it doesn't work.

Reproduction steps

  1. set up a form with an array-field and useFiledArray
  2. set up some validation on the fieldarray
  3. try accessing the specific errors for the fields contained in the fieldarray (like above)

Version

Vue.js 3.x and vee-validate 4.x

What browsers are you seeing the problem on?

  • Firefox
  • Chrome
  • Safari
  • Microsoft Edge

Relevant log output

No response

Demo link

ihavenoideahowtosetupcodepenwithvueandTS.sorry

Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions