How to solve this typescript check issue?

I am using typescript in Moralis, how to solve this type check issue?

image

import Moralis from "moralis";
import { useEffect, useState, useCallback } from "react";
import { Text, Divider, Image } from "@chakra-ui/react";
import { useMoralisWeb3Api } from "react-moralis";
import CustomContainer from "../CustomContainer";

type MyProps = {
  account: string;
};

function Balance({ account }: MyProps) {
  const Web3API = useMoralisWeb3Api();
  const chainId = Moralis.getChainId();

  const [ethBalance, setEthBalance] = useState();
  const [tokBalance, setTokBalance] = useState();

  // 1. Native Balance
  const fetchNativeBalance = useCallback(async () => {
    const nativeBala = await Web3API.account.getNativeBalance({
      chain: chainId,
      address: account,
    });
    if (nativeBala && nativeBala.balance) {
      setEthBalance(Moralis.Units.FromWei(nativeBala.balance));
    }
  }, [Web3API.account, account, chainId]);

Type ‘string | null’ is not assignable to type ‘“eth” | “0x1” | “ropsten” | “0x3” | “rinkeby” | “0x4” | “goerli” | “0x5” | “kovan” | “0x2a” | “polygon” | “0x89” | “mumbai” | “0x13881” | “bsc” | “0x38” | “bsc testnet” | “0x61” | … 6 more … | undefined’.
Type ‘null’ is not assignable to type ‘“eth” | “0x1” | “ropsten” | “0x3” | “rinkeby” | “0x4” | “goerli” | “0x5” | “kovan” | “0x2a” | “polygon” | “0x89” | “mumbai” | “0x13881” | “bsc” | “0x38” | “bsc testnet” | “0x61” | … 6 more … | undefined’.ts(2322)
useMoralisWeb3Api.d.ts(251, 13): The expected type comes from property ‘chain’ which is declared here on type ‘{ chain?: “eth” | “0x1” | “ropsten” | “0x3” | “rinkeby” | “0x4” | “goerli” | “0x5” | “kovan” | “0x2a” | “polygon” | “0x89” | “mumbai” | “0x13881” | “bsc” | “0x38” | “bsc testnet” | … 7 more … | undefined; providerUrl?: string | undefined; to_block?: number | undefined; } & { …; }’

I have tried below way, no effect.

Does this work?

const chainId = Moralis.getChainId() as ChainType;

2 Likes

Thanks, it worked, solved.
And, may I know, if I delete line 10…