Search code examples
reactjstypescriptsolidityweb3jsabi

How do you set types on getting Object.keys on JSON file in TypeScript?


I am trying to access an object from a JSON file and the error I am getting:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{...}'. ts(7053)

JSON file:

"networks": {
  "5777": {
    "event": {},
    "links": {},
    "address": "string",
    "transactionHash": "string"
  }
}

The value 5777 will be changed from time to time. So I am trying to access the value, which gives me an error.

Snippet from TS file:

import { abi, networks } from '../build/contracts/Example.json';
import Web3 from 'web3';
let networkId: any = Object.keys(networks)[0]; // 5777
new web3.eth.Contract(abi, networks[networkId].address); // causing error

Solution

  • You can cast it manually

    let networkId = Object.keys(networks)[0] as keyof typeof networks; // 5777