Web3开发新手遭遇TypeScript类型不兼容错误求助
解决方案
你的两个TypeScript错误源于MetaMask Provider的事件回调参数类型不匹配:TypeScript无法推断accountsChanged和networkChanged事件的参数类型,默认将其视为unknown[],与你指定的string[]/string类型冲突。以下是两种修复方式:
方式一:类型断言 + 修正类型不匹配
直接在回调中对参数进行类型断言,同时注意networkChanged返回的是字符串类型的链ID,需要转为数字以匹配你的IWeb3State定义:
useEffect(() => { if (typeof window.ethereum === "undefined") return; window.ethereum.on("accountsChanged", (accounts) => { // 断言参数为string[]类型 const userAccounts = accounts as string[]; setState({ ...state, address: userAccounts[0] || null }); }); window.ethereum.on("networkChanged", (network) => { // 断言参数为string并转为数字 const chainId = Number(network as string); setState({ ...state, currentChain: chainId }); }); return () => { window.ethereum?.removeAllListeners(); }; }, [state]);
方式二:利用MetaMask类型定义明确事件类型
导入@metamask/providers的事件类型,明确指定回调参数类型:
// 先导入ProviderEvent类型 import { MetaMaskInpageProvider, ProviderEvent } from "@metamask/providers"; // 然后修改useEffect部分 useEffect(() => { if (typeof window.ethereum === "undefined") return; window.ethereum.on("accountsChanged" as ProviderEvent, (accounts: string[]) => { setState({ ...state, address: accounts[0] || null }); }); window.ethereum.on("networkChanged" as ProviderEvent, (network: string) => { setState({ ...state, currentChain: Number(network) }); }); return () => { window.ethereum?.removeAllListeners(); }; }, [state]);
补充说明
你的IWeb3State中currentChain定义为number | null,但networkChanged事件返回的是字符串格式的链ID(比如"1"代表以太坊主网),因此必须用Number()转换类型,否则会触发新的类型不匹配错误,上述代码已包含该修正。
内容的提问来源于stack exchange,提问作者King Lawson
相关产品推荐
相关产品推荐

