简体   繁体   中英

How to type a JSON import in TypeScript

Basically I want to type an imported JSON so I could inspect it easily. This is what Ive tried:

// typings.d.ts

type NetWorkReport = {
  log: {
    version: string
    creator: any
    pages: any[]
    entries: Request[]
  }
}

declare module "*.json" {
  const value: NetWorkReport;
  export default value;
}

And my code where I import the file:

// index.ts

import * as networkCapture from './networkCapture.json';

console.log(networkCapture.log) // ERROR: Property 'log' does not exist on type '{}'

My JSON is huge (Its actually an export from Chrome DevTools > Network > Export HAR... ). The first lines are:

{
  "log": {
    "version": "1.2",
    "creator": {
      "name": "WebInspector",
      "version": "537.36"
    },
    "pages": [
      {
        "startedDateTime": "2020-03-11T12:21:37.400Z",
        "id": "page_1",
        "title": "https://somewebpage.com",
        "pageTimings": {
          "onContentLoad": 1946.7949999962002,
          "onLoad": 3050.905000010971
        }
      }
    ],

...

What Im doing wrong?

I have also import the json file on .ts page.

import like.

import * as countries from '../../../environments/countries.json';

and than get the data in constructor like this.

let countriesList: any = [];
countriesList = countries;

So you can do like this to get your Json data.

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