gpt4 book ai didi

reactjs - typescript 错误 : Type 'string' is not assignable to type '"allName"| `allName.${number}.nestedArray` ' in react hook form

转载 作者:行者123 更新时间:2023-12-04 11:56:36 25 4
gpt4 key购买 nike

我正在使用 typescript 处理 react 钩子(Hook)表单。我的数据结构在数组中看起来是数组。所以我尝试使用 useFieldArray

allName: [
{
name: "useFieldArray1",
nestedArray: [
{ name1: "field1", name2: "field2" },
{ name1: "field3", name2: "field4" }
]
},
{
name: "useFieldArray2",
nestedArray: [{ name1: "field1", name2: "field2" }]
}
]
但是当我尝试为输入设置名称时,如 allName[${nestIndex}].nestedArray我收到以下警告。
Type 'string' is not assignable to type '"allName" | `allName.${number}.nestedArray`'
在这里我附上了我的代码的代码沙箱链接。
https://codesandbox.io/s/gallant-buck-iyqoc?file=/src/nestedFieldArray.tsx:504-537
如何解决这个问题?

最佳答案

你好,我看到的几件事,

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 see you have ` vs ' ticks/quote


  • 附: const适用于较新/较新版本的 Tyspescript 编译器,但如果您更改它,则适用于旧版本 any它应该工作!
  •  //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`

    关于reactjs - typescript 错误 : Type 'string' is not assignable to type '"allName"| `allName.${number}.nestedArray` ' in react hook form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68064003/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com