【问题标题】:Typescript error: Type 'string' is not assignable to type '"allName" | `allName.${number}.nestedArray`' in react hook form打字稿错误:类型 'string' 不可分配给类型 '"allName" | `allName.${number}.nestedArray`' 在反应钩子形式
【发布时间】:2021-09-04 21:27:03
【问题描述】:

我正在使用 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 如何解决这个问题?

【问题讨论】:

  • 你的 nestedIndex 属性 NestedFieldArray 被声明为类型 string,但它在 <Fields> 组件中传递了一个数字。它应该是一个数字。方括号可能是不必要的,名称应该是 `allName.${nestIndex}.nestedArray` as const 以匹配 the documentation 所说的内容。
  • @Calvin 我按照您的建议进行了更改。我仍然遇到同样的问题。 codesandbox.io/s/pedantic-fermi-rvuzq?file=/src/…
  • @Calvin 第 15 行的问题
  • as const 附加到该行是否有效?
  • @Calvin 该错误现已解决。我面临一个问题,我的表单未使用默认值呈现。输入在初始时间为空。但是,默认值有一些有效值。 codesandbox.io/s/vigilant-cori-36ose?file=/src/…

标签: reactjs typescript react-hook-form


【解决方案1】:

你好,我看到了几件事,

1) 您必须将其cast 设置为您导出的类型,或者明确地将const compiler needs to be aware of the type

2) 我还注意到你有` vs ' ticks/quote

3。附言。 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` 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-09
    • 2021-09-11
    • 2017-04-23
    • 2022-08-14
    • 2018-02-02
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多