`Property 'ethereum' does not exist on type 'Window & typeof globalThis'` error in React

Viewed 7677

I am getting the

Property 'ethereum' does not exist on type 'Window & typeof globalThis'

error in React. This is the line generating the issue:

import { ethers } from 'ethers'

const provider = new ethers.providers.Web3Provider(window.ethereum);

Any idea of what could be happening?

3 Answers

Create the react-app-env.d.ts file in the src folder with the following script:

/// <reference types="react-scripts" />

interface Window {
    ethereum: any
}

Using any as a type is cheating.

import { MetaMaskInpageProvider } from "@metamask/providers";

declare global {
  interface Window{
    ethereum?:MetaMaskInpageProvider
  }
}

In my src/react-app-env.d.ts I am using

/// <reference types="react-scripts" />
import { ExternalProvider } from "@ethersproject/providers";

declare global {
  interface Window {
    ethereum?: ExternalProvider;
  }
}

Notice that @ethersproject/providers is an ethers dependency so you do not need to install it.

Then I also added a src/hooks/useMetaMask.ts file with useMetaMask hook that casts the provider to MetaMask provider type. This can be useful if you need to add MetaMask listeners.

import type { MetaMaskInpageProvider } from "@metamask/providers";

export const useMetaMask = () => {
  const ethereum = global?.window?.ethereum;
  if (!ethereum || !ethereum.isMetaMask) return;
  return ethereum as unknown as MetaMaskInpageProvider;
};
Related