react-moralis
react-moralis copied to clipboard
Typescript support for `chain` is not working and the web3 example in the docs is broken
New Bug Report
Checklist
- [x] I am not disclosing a vulnerability.
- [x] I have searched through existing issues and the Moralis Forum.
- [x] I can reproduce the issue with the latest react-moralis release, latest SDK release, and my server is updated to the latest version.
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
- The
useMoralisWeb3ApiCallfunction does not exist - 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
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
yeah man this is a lame library, when you use typescript you should know how to use it properly