turf icon indicating copy to clipboard operation
turf copied to clipboard

turf/length typings don't support passing a geometry

Open pavloconuve opened this issue 2 years ago • 2 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.

pavloconuve avatar Aug 18 '23 10:08 pavloconuve

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!

JamesLMilner avatar Aug 20 '23 10:08 JamesLMilner

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}`);

bejago avatar Sep 10 '23 07:09 bejago