【问题标题】:Type 'string' is not assignable to type keyof [Type]类型“字符串”不可分配给类型 keyof [Type]
【发布时间】:2019-06-04 22:31:21
【问题描述】:

我希望有人可以帮助解决这个问题。我对打字稿反应世界很陌生,我写了一个 Textarea 子组件,它把一个函数作为一个 onChange 道具。 然后使用 2 个字符串作为子组件的参数调用此函数。

在父组件中,我更具体地知道该函数调用的第二个参数应该是什么样子(keyof Type)。问题是,打字稿告诉我 type string 不可分配给 type [insert strings of keys of Type]。

我认为它应该通过使用泛型来解决?但我根本无法理解它。

我试过这个how can you express "keyof T" to be a subset of String?,但错误不会消失。

准系统代码可以在这里找到:https://codesandbox.io/s/modest-dhawan-v3z2y 在此示例中,第一个和第三个 Textarea 不应引发任何错误,因为第二个参数将是指定类型之外的键。

我该如何解决这个问题?

我希望 index.tsx 中的两个 Textarea 组件都不会引发任何类型错误,我再次认为泛型可能是解决方案,但我无法弄清楚。

先谢谢了。

【问题讨论】:

  • 不需要泛型也不需要第二个参数。当您将该参数的值作为道具传递时,这表明您已经知道父组件中的值是什么
  • 我不敢相信我自己没有弄清楚这一点。它是如此容易。解决了这个问题,非常感谢。
  • 不用担心,我只是将此提升为一个答案,以便让我获得一些多汁的代表点业力。

标签: reactjs typescript


【解决方案1】:

不需要泛型,也不需要第二个参数。当您将该参数的值作为道具传递时,它表明您已经知道父组件中的值将是什么。您可以传递 lambda 或已设置名称的绑定函数。

      <TextArea
        id="ErrorDescription"
        name="ErrorDescription"
        className="form-control"
        isRequired
        value={inputValues.ErrorDescription}
        onChange={(value) => updateValue(value, 'ErrorDescription')}
      />

或者

// Note I had to swap the order of parameters to facilitate binding
const updateValue = (eventtargetname: keyof InputValues, eventvalue: string) => ...

const updateErrorValue = updateValue.bind(this, 'ErrorDescription')

return (
  ...
  <TextArea
        id="ErrorDescription"
        name="ErrorDescription"
        className="form-control"
        isRequired
        value={inputValues.ErrorDescription}
        onChange={updateErrorValue}
  />
)

就我个人而言,我会选择 lambda,因为它们更简洁。绑定函数在渲染函数之外使用时在类组件中表现更好,但在函数和钩子范式中不再可能。

工作示例。 https://codesandbox.io/s/quizzical-darkness-79eux

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 2021-02-22
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多