打字稿:“字符串”类型的参数不可分配给字符串类型的参数

时间:2021-01-07 23:56:26

标签: typescript

screenshot of error

我收到此错误 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 在这里失败?

1 个答案:

答案 0 :(得分:0)

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

通俗地说,wallet.connect() 只接受所有 string 值的一个子集,但您为其提供了任何 string 值。这就是错误的主要原因:类型不兼容。

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

相关问题