【问题标题】:Typescript: Argument of type 'string' is not assignable to parameter of type string打字稿:“字符串”类型的参数不可分配给字符串类型的参数
【发布时间】:2021-01-08 08:09:10
【问题描述】:

我收到此错误Argument of type 'string' is not assignable to parameter of (a list of strings)

useEffect(() => {
    if (selectedConnection) {
      wallet.connect(selectedConnection)
    }
  }, [selectedConnection])

selectedConnection 是一个字符串,wallet.connect 接受一个字符串。

我已经改成

selectedConnection:
    | null
    | 'authereum'
    | 'fortmatic'
    | 'frame'
    | 'injected'
    | 'portis'
    | 'squarelink'
    | 'provided'
    | 'torus'
    | 'walletconnect'
    | 'walletlink'

它有效。

为什么这甚至是必要的?

为什么 Typescript 在这里失败了?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    因为selectedConnection 是任意字符串值的string,而wallet.connect 接受特定联合类型字符串的参数。这就是为什么。如果在调用 wallet.connect() 之前不确定它的可能值是什么,则需要为 selectedConnection 添加类型保护。

    用外行的话来说,wallet.connect() 只接受所有 string 值的子集,但您为它提供了 any string 值。这是错误的主要原因:类型不兼容。

    出于这个原因,这就是为什么当您将selectedConnection 的类型缩小为联合类型时它会再次起作用,因为现在selectionConnection 的类型与wallet.connection() 接受的参数类型兼容.

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2019-10-30
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2021-10-13
      • 2020-03-09
      相关资源
      最近更新 更多