2

I have written the following in typescript for a dynamic form

type FormData = {
    name: string,
    session: { name: string }[]
}

...

const { control, register, handleSubmit } = useForm<FormData>()
const { fields, insert, remove, move, append } = useFieldArray({
    control,
    name: "session",
    keyName: "id"
})

...

{
    fields.map((field, index) => {
        return <div key={field.id}>
            <div>
                <label>Session {index}</label>
                <input type={"text"} {...register(`session.${index}.name`)} />
            </div>
        </div>
    })
}


and I get the error at the part {...register(session.${index}.name)}

Argument of type 'string' is not assignable to parameter of type '"session" | "name" | session.${number} | session.${number}.name' ts(2345)

The error goes away when i dont pass in FormData

const { control, register, handleSubmit } = useForm()

1 Answer 1

2

in v7, register() accepts a literal (an exact string value) instead of a string. So change your code to:

<input type={"text"} {...register(`session.${index}.name` as const)} />

To avoid type widening. See const assertions.

Related question:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.