我遇到了这个错误 Argument of type 'string' is not assignable to parameter of (a list of strings) .
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
wallet.connect
我把它改成了
selectedConnection: | null | 'authereum' | 'fortmatic' | 'frame' | 'injected' | 'portis' | 'squarelink' | 'provided' | 'torus' | 'walletconnect' | 'walletlink'
它奏效了。
为什么这是必要的?
为什么Typescript在这里失败了?
因为 selectedConnection 是a string 任意字符串值,而 wallet.connect 接受特定联合类型的字符串。这就是为什么。您需要为以下内容添加一个类型保护 selected连接 ,如果你不确定它的可能值是什么,在调用之前 wallet.connect() .
string
selected连接
wallet.connect()
用外行的话来说, wallet.connect() 只接受全部的子集 一串 值,但您正在提供它 任何 一串 价值。这是错误的主要原因:类型不兼容。
一串
出于这个原因,这就是为什么当你缩小类型 selected连接 对于联合类型,它会再次工作,因为现在的类型 selectionConnection 与接受的参数类型兼容 wallet.connection() .
selectionConnection
wallet.connection()