简体   繁体   中英

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

You can cast it manually

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

Firstly i upvoted the @ABOS answer, and in enhancement and as a detailed have mentioned following source code for contract data creation using abi

import Web3 from 'web3'
import ElectionCommission, { networks as ecNetworks} from "./truffle_abis/ElectionCommission.json";

let networkId = Object.keys(ecNetworks)[0] as keyof typeof ecNetworks;
let ecCommissionData = new web3.eth.Contract(ElectionCommission.abi as any, ecNetworks[networkId].address);

Hope this would help manyones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM