TypeScript – 类型 ‘string’ 无法赋值给类型 ‘0x${string}’。

huangapple go评论59阅读模式
英文:

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],
});

huangapple
  • 本文由 发表于 2023年7月20日 16:57:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定