Turfjs / turf

A modular geospatial engine written in JavaScript and TypeScript

Home Page:https://turfjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

turf/length typings don't support passing a geometry

mykhalov opened this issue · comments

Passing a geometry to turf/length will result in a TypeScript error:

import length from "@turf/length";
import { lineString } from "@turf/helpers";

const feature = lineString([
  [0, 0],
  [0, 1],
  [1, 1],
]);

length(feature.geometry);
$ npx tsc index.ts
index.ts:10:8 - error TS2345: Argument of type 'LineString' is not assignable to parameter of type 'GeometryCollection | Feature<any, { [name: string]: any; }> | FeatureCollection<any, { [name: string]: any; }>'.
  Property 'features' is missing in type 'LineString' but required in type 'FeatureCollection<any, { [name: string]: any; }>'.

10 length(feature.geometry);
          ~~~~~~~~~~~~~~~~

  node_modules/@turf/helpers/dist/js/lib/geojson.d.ts:192:5
    192     features: Array<Feature<G, P>>;
            ~~~~~~~~
    'features' is declared here.


Found 1 error in index.ts:10

The function itself seems to have no problem calculating the length of a geometry: adding @ts-ignore above yields a result, 222.3732244879406.

Turf version: 6.5.0.

Hey, thanks for raising. I think length expects a Feature rather than a Geometry: https://turfjs.org/docs/#length

I am surprised the length works with passing the geometry; assumedly this is because under the hood it gets passed from -> segmentReduce -> segmentReduce -> segmentEach -> flattenEach -> flattenEach which from briefly looking looks like it normalises everything to a geometry.

I don't think is documented behaviour and so think the TypeScript error is probably justified. Happy for other people to chime in with thoughts!

commented
import length from "@turf/length";
import { lineString, feature } from "@turf/helpers";

const line = lineString([
  [0, 0],
  [0, 1],
  [1, 1],
]);

const lineFeature = feature(line.geometry);

const result = length(lineFeature);

console.log(`The length is: ${result}`);