[英]`Property 'ethereum' does not exist on type 'Window & typeof globalThis'` error in React
I am getting the我得到了
Property 'ethereum' does not exist on type 'Window & typeof globalThis'类型“Window & typeof globalThis”上不存在属性“ethereum”
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?知道会发生什么吗?
Using any
as a type is cheating.使用any
作为类型是作弊。
import { MetaMaskInpageProvider } from "@metamask/providers";
declare global {
interface Window{
ethereum?:MetaMaskInpageProvider
}
}
Create the react-app-env.d.ts
file in the src
folder with the following script:使用以下脚本在src
文件夹中创建react-app-env.d.ts
文件:
/// <reference types="react-scripts" />
interface Window {
ethereum: any
}
In my src/react-app-env.d.ts I am using在我的src/react-app-env.d.ts我正在使用
/// <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.请注意, @ethersproject/providers
是一个ethers
依赖项,因此您不需要安装它。
Then I also added a src/hooks/useMetaMask.ts file with useMetaMask
hook that casts the provider to MetaMask provider type.然后我还添加了一个带有useMetaMask
钩子的src/hooks/useMetaMask.ts文件,它将提供者转换为 MetaMask 提供者类型。 This can be useful if you need to add MetaMask listeners.如果您需要添加 MetaMask 侦听器,这会很有用。
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.