代码之家  ›  专栏  ›  技术社区  ›  GN.

Typescript:类型为“string”的参数不能分配给类型为string的参数

  •  0
  • GN.  · 技术社区  · 5 年前

    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 回复  |  直到 5 年前
        1
  •  2
  •   Terry    5 年前

    因为 selectedConnection 是a string 任意字符串值,而 wallet.connect 接受特定联合类型的字符串。这就是为什么。您需要为以下内容添加一个类型保护 selected连接 ,如果你不确定它的可能值是什么,在调用之前 wallet.connect() .

    用外行的话来说, wallet.connect() 只接受全部的子集 一串 值,但您正在提供它 任何 一串 价值。这是错误的主要原因:类型不兼容。

    出于这个原因,这就是为什么当你缩小类型 selected连接 对于联合类型,它会再次工作,因为现在的类型 selectionConnection 与接受的参数类型兼容 wallet.connection() .

    推荐文章