I am working on the react hook form with typescript. My data structure looks array within array. so I try to use the useFieldArray
allName: [
{
name: "useFieldArray1",
nestedArray: [
{ name1: "field1", name2: "field2" },
{ name1: "field3", name2: "field4" }
]
},
{
name: "useFieldArray2",
nestedArray: [{ name1: "field1", name2: "field2" }]
}
]
But when I try to set the name for the input like allName[${nestIndex}].nestedArray
I got the below warning.
Type 'string' is not assignable to type '"allName" | `allName.${number}.nestedArray`'
Here I have attached the code sandbox link of my code. https://codesandbox.io/s/gallant-buck-iyqoc?file=/src/nestedFieldArray.tsx:504-537 How to fix this issue?
Hello couple things I see,
1
) you have tocast
it to that type that you exported orconst
thecompiler needs to be aware of the type
explicitly.
2
) I also noticed you have ` vs'
ticks/quote
3
. ps.const
works on the later/newer version of Tyspescript compiler, but for older versions if you change itany
it should work!
//option 1
name: `allName.${nestIndex}.nestedArray` as const
// option 2 for older versions
name: `allName.${nestIndex}.nestedArray` as any
// or if assigning a variable, but it wont work in your code
// let name = <const> `allName.${nestIndex}.nestedArray`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With