Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript error: Type 'string' is not assignable to type '"allName" | `allName.${number}.nestedArray`' in react hook form

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?

like image 233
Gmv Avatar asked Jun 21 '21 07:06

Gmv


1 Answers

Hello couple things I see,

1) you have to cast it to that type that you exported or const the compiler 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 it any 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` 
like image 131
Transformer Avatar answered Nov 20 '22 03:11

Transformer