[英]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.我正在使用打字稿处理 react hook 表单。 My data structure looks array within array.
我的数据结构在数组中看起来是数组。 so I try to use the
useFieldArray
所以我尝试使用
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.但是当我尝试为像
allName[${nestIndex}].nestedArray
这样的输入设置名称时,我收到了以下警告。
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?
https://codesandbox.io/s/gallant-buck-iyqoc?file=/src/nestedFieldArray.tsx:504-537如何解决这个问题?
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.1
) 您必须cast
其const
为导出的类型,或者compiler needs to be aware of the type
显式地compiler needs to be aware of the type
。2
) I see you have ` vs'
ticks/quote2
) 我看到你有 ` vs'
刻度/引号
const
works on the later/newer version of Tyspescript compiler, but for older versions if you change it any
it should work! 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`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.