Search code examples
typescriptethereummetamask

How to handle a return type Maybe<unknown>


Iam using typescript and iam trying to get the accounts from the current user like its showed on the metamask official documentation Metamask Doc:

const accounts = await window.ethereum.request({
                  method: "eth_accounts",
                }); 

The call to the request function returns a result with the Maybe<unknown> type.

Then iam trying to access the first element of accounts like this because its supposed to be an array of string :

accounts[0]

But i have the following errors:

Object is possibly 'null' or 'undefined'.ts(2533)

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Partial<unknown>'.
  Property '0' does not exist on type 'Partial<unknown>'.ts(7053)

So, how can i manage to handle this situation? I need to properly get the return of the request function and make typescript accept it as an array of string.

Thanks.


Solution

  • The errors indicate that the returned value from the request might be null, undefined or even not-an-array value. So you have to check those cases before accessing its value.

    const accounts = await window.ethereum.request({
      method: "eth_accounts",
    }); 
    if (accounts && Array.isArray(accounts)) {
      // Here you can access accounts[0]
    } else {
      // Handle errors here if accounts is not valid. 
    }