GN.
GN.

Reputation: 9899

Typescript: Argument of type 'string' is not assignable to parameter of type string

screenshot of error

I am getting this error Argument of type 'string' is not assignable to parameter of (a list of strings).

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

selectedConnection is a string and wallet.connect takes a string.

I've changed it to

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

and it works.

Why is this even necessary?

Why does Typescript fail here?

Upvotes: 2

Views: 1306

Answers (1)

Terry
Terry

Reputation: 66228

Because selectedConnection is a string of any arbitrary string value, while wallet.connect accepts an arugment that is of a specific union type of strings. That's why. You will need to add a type guard for selectedConnection, if you are not sure what its possible values are, prior to invoking wallet.connect().

In layman's terms, wallet.connect() only accepts a subset of all string values, but you are providing it with any string value. That is the main reason of the error: type incompatibility.

And for that reason, that is why when you narrow the type of selectedConnection to a union type then it works again, because now the type of selectionConnection is compatible with the type of the argument accepted by wallet.connection().

Upvotes: 2

Related Questions