react-moralis icon indicating copy to clipboard operation
react-moralis copied to clipboard

Typescript support for `chain` is not working and the web3 example in the docs is broken

Open vomc opened this issue 3 years ago • 2 comments

New Bug Report

Checklist

Issue Description

Try to run the runContractFunction example as listed in the moralis docs here: https://docs.moralis.io/moralis-dapp/web3-api/native#runcontractfunction

Actual Outcome

  1. The useMoralisWeb3ApiCall function does not exist
  2. You get a crashed app because the typing of a string for the chain (e.g. eth) will not work, i.e.
const options = {
    chain: "eth",
...

will result in

Type 'string' is not assignable to type '"0x61" | "bsc testnet" | "eth" | "0x1" | "ropsten" | "0x3" | "rinkeby" | "0x4" | "goerli" | "0x5" | "kovan" | "0x2a" | "polygon" | "0x89" | "mumbai" | "0x13881" | "bsc" | "0x38" | ... 6 more ... | undefined'.

Expected Outcome

Somehow I thought that for a 'developer-friendly' toolset the examples in the public documentation would work...

Client

  • react-moralis version: 1.3.5
  • Moralis SDK version: 1.6.0

vomc avatar May 02 '22 16:05 vomc

This is an issue with Typescript. When you define your options object, Typescript will infer the chain type as a string.

You can avoid this by narrowing the type like:

when the options are static:

const options = {
    chain: 'eth',
    block_number_or_hash: ""
  } as const

Or otherwise something similar as this:

  const chain: Moralis.Chain = 'eth'
  const options = {
    chain,
    block_number_or_hash: ""
  }

Another approach is to defined the options directly in the function call, and not beforehand:

useMoralisWeb3ApiCall(Moralis.Web3API.native.getBlock, {
    chain: 'eth',
    block_number_or_hash: ""
  })

There are several approaches you can take, depending on your needs and code structure. You basically want to tell Typescript that chain is not just any string, but only a valid Chain type

ErnoW avatar May 02 '22 16:05 ErnoW

yeah man this is a lame library, when you use typescript you should know how to use it properly

x5engine avatar Jul 19 '22 10:07 x5engine