Home > Blockchain >  Why does my TS file thinks a JSON array is an object?
Why does my TS file thinks a JSON array is an object?

Time:04-12

I'm trying to import a really large JSON file inside a TypeScript file. When I use it my IDE tells me that Property 'length' does not exist on type '{}', when the JSON is clearly an array. How could I fix this?

This is my code:

TS file:

import cities from "./cities.json"

const printData = () => {
    console.log(cities.length)
}

JSON file:

[
    { "country": "Andorra", "name": "Sant Julià de Lòria" },
    { "country": "Andorra", "name": "Pas de la Casa" },
    { "country": "Andorra", "name": "Ordino" },
    { "country": "Andorra", "name": "les Escaldes" },
    { "country": "Andorra", "name": "la Massana" },
    { "country": "Andorra", "name": "Encamp" },
    ...   128K more objects
]

I've seen that it can come from the size of the file, and that I should use a .d.ts file to declare it. I tried this:

let cities: {
    country: string
    name: string
}[]

export declare module "./cities.json" {
    cities
}

But to call the object I need to call it twice like this:

import cities from "./cities"

const printData = () => {
    console.log(cities.cities.length)
}

How could I fix this? Thanks!

CodePudding user response:

Actually, I think this approach is useful. The only thing that you could change is the way that you are importing the information. You can destructure the object that you are importing.

Before:

import cities from "./cities"

After

import {cities} from "./cities"

With that you can use cities.length with no hesitation!

CodePudding user response:

You can use object destructuring to get cities out of cities. For a simple one-liner solution, use this code.

import { cities } from "./cities";

This means that you can use only one cities for getting the length!

cities.length;

This will solve your issue, and also increase code readability.

  • Related