How to type GeoJSON objects with custom properties in TS/JS

Just a quick note because I found this useful and the @types/geojson docs aren’t especially verbose.


Type a GeoJSON returned from a fetch (TypeScript)

import type { FeatureCollection, Geometry } from 'geojson';

// Create a standard GeoJSON object with custom properties for each feature:
type MyFeatureCollection = FeatureCollection<
    Geometry,
    {
      // Your types go here
      name: string;
      id: string;
      height?: number;
      color?: string;
    }
  >;

// Fetch and apply types to our GeoJSON obj
const myGeoJSON = await fetch('/au.geo.json')
  .then(res => res.json() as Promise<MyFeatureCollection>);

At this point you get autocomplete in VSCode Intellisense (or equivalent), for standard GeoJSON props, as well as your own custom properties. Pretty cool.

In VSCode, accessing properties on a GeoJSON feature shows a dropdown with recommendations based on our types.

Type a GeoJSON returned from a fetch (JSDoc)

Same again, but in Javascript, NodeJS etc:

/**
 * @typedef {import('geojson').FeatureCollection<
 *   import('geojson').Geometry,
 *   {
 *     name: string;
 *     id: string;
 *     height?: number;
 *     color?: string;
 *   }
 * >} MyFeatureCollection
 */

const myGeoJSON = await fetch('/au.geo.json')
  .then(res => /** @type {Promise<MyFeatureCollection>} */ (res.json()))

Leave a Reply

Your email address will not be published. Required fields are marked *