在 TypeScript 中,如何在 JSON 文件上设置获取 Object.keys 的类型?
How do you set types on getting Object.keys on JSON file in TypeScript?
我正在尝试从 JSON 文件访问一个对象,我得到的错误是:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{...}'. ts(7053)
JSON 文件:
"networks": {
"5777": {
"event": {},
"links": {},
"address": "string",
"transactionHash": "string"
}
}
值5777
会不时更改。所以我试图访问该值,这给了我一个错误。
来自 TS 文件的片段:
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
你可以手动施法
let networkId = Object.keys(networks)[0] as keyof typeof networks; // 5777
首先我赞成 @ABOS
答案,在增强和详细说明中提到了使用 abi
创建 contract data
的以下源代码
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);
希望对大家有所帮助。
我正在尝试从 JSON 文件访问一个对象,我得到的错误是:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{...}'. ts(7053)
JSON 文件:
"networks": {
"5777": {
"event": {},
"links": {},
"address": "string",
"transactionHash": "string"
}
}
值5777
会不时更改。所以我试图访问该值,这给了我一个错误。
来自 TS 文件的片段:
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
你可以手动施法
let networkId = Object.keys(networks)[0] as keyof typeof networks; // 5777
首先我赞成 @ABOS
答案,在增强和详细说明中提到了使用 abi
contract data
的以下源代码
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);
希望对大家有所帮助。