【问题标题】:How do you set types on getting Object.keys on JSON file in TypeScript?如何在 TypeScript 中获取 JSON 文件上的 Object.keys 时设置类型?
【发布时间】:2023-03-16 14:46:01
【问题描述】:

我正在尝试从 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

【问题讨论】:

    标签: typescript web3js


    【解决方案1】:

    你可以手动投射

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

    【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2021-12-19
    • 2013-01-12
    相关资源
    最近更新 更多