英文:
typescript - Type 'string' is not assignable to type '`0x${string}`
问题
以下是翻译好的部分:
"我正在使用React TypeScript开发我的NFT项目,使用wagmi。
在开发NFT检查模块时,我遇到了这个错误:
类型 'string' 无法分配给类型 '
0x${string}
'
如何将我的字符串转换为 0x${string}
?
以下是我的代码:
import { useEffect, useState } from "react";
import { useContractRead, erc721ABI } from "wagmi";
const useNFTChecker = ({
contractAddress,
walletAddress,
}: {
contractAddress: string;///<-- this needs conversion
walletAddress: string;
}) => {
const { data, error } = useContractRead({
address: contractAddress, ///<-- `0x${string}`
contractInterface: erc721ABI,
functionName: "balanceOf",
args: [walletAddress],
});
const [hasNFT, setHasNFT] = useState(false);
...
return { hasNFT, error };
};
export default useNFTChecker;
希望这能帮助你解决问题。
英文:
I am using wagmi for my NFT project using react typescript.
when developing the NFT checking module I got this error:
> Type 'string' is not assignable to type '0x${string}
'
how do I cast my string into 0x${string}
?
below are my code:
import { useEffect, useState } from "react";
import { useContractRead, erc721ABI } from "wagmi";
const useNFTChecker = ({
contractAddress,
walletAddress,
}: {
contractAddress: string;///<-- this needs conversion
walletAddress: string;
}) => {
const { data, error } = useContractRead({
address: contractAddress, ///<-- `0x${string}`
contractInterface: erc721ABI,
functionName: "balanceOf",
args: [walletAddress],
});
const [hasNFT, setHasNFT] = useState(false);
...
return { hasNFT, error };
};
export default useNFTChecker;
答案1
得分: 2
我遇到了一个类似的问题,需要将字符串强制转换为地址字符串。我通过使用 as
来断言字符串类型为 0x${string}
来解决了这个问题。
基本上,尝试使用以下方法,看看是否修复了 TypeScript 错误。
const { data, error } = useContractRead({
address: contractAddress as `0x${string}`,
contractInterface: erc721ABI,
functionName: "balanceOf",
args: [walletAddress],
});
英文:
I had a similar problem with needing to typecast string into an address string. I fixed the issue by asserting the string type to 0x${string}
using as
.
Basically try using the following and see if it fixes the TypeScript error.
const { data, error } = useContractRead({
address: contractAddress as `0x${string}`,
contractInterface: erc721ABI,
functionName: "balanceOf",
args: [walletAddress],
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论