Search code examples
typescriptcastingtypescript-namespace

Typescript for parsed data - geojson


I have a simple typescript app using vite that is supposed to rad a geojson and display it as a map. Simple enough, but as I'm not extremely proficient with typescript, I ran into a problem:

//importing the file as a string, I declared a module that types it correctly
import worldGeoJson from '@/assets/world.geojson?raw'

const worldJson = JSON.parse(worldGeoJson)

Now, the problem I ran into is that worldJson has now type any. So, I installed @types/geojson and tried to simply assign it like:

const worldJson: GeoJSON = JSON.parse(worldGeoJson)

but now I'm getting a message of Cannot use namespace 'GeoJSON' as a type. - fair enough, but I have failed in my attempts of casting it into a type. I guess I could import all types inside geojson type file and reconstruct it myself but I have a feeling it would defeat the purpose of the exercise.


Solution

  • You can also import types, including named exported types, in the same manner as usual JS modules:

    // Import the named export "FeatureCollection" from @types/geojson
    import type { FeatureCollection } from "geojson";
    
    // JSON.parse has no way to know the resulting type,
    // so we have to specify it with a type assertion
    const worldJson = JSON.parse("string GeoJSON FeatureCollection") as FeatureCollection;
    //    ^? FeatureCollection<Geometry, GeoJsonProperties>
    
    // Then we can safely use the object
    worldJson.features; // Okay
    //        ^? Feature<Geometry, GeoJsonProperties>[]
    
    

    Playground Link