Turf.jsAssertions

turf.collectionOf

What is turf.collectionOf?

turf.collectionOf is a runtime assertion helper. It throws an Error if any Feature inside a FeatureCollection does not have the expected geometry type. It is used internally by Turf functions that require homogeneous input and is exposed so you can reuse the same checks in your own code.

JavaScript
turf.collectionOf(featureCollection, type, name)void

Parameters:

  • featureCollection — the collection to validate
  • type — the GeoJSON type string every Feature must match (e.g. 'Point')
  • name — the caller's function name, included in the thrown message

When would you use turf.collectionOf?

Use turf.collectionOf inside your own functions when you require a specific geometry type — a clustering helper that only accepts Points, a polygon-dissolve wrapper that needs Polygons. The thrown error message is clear enough to debug callers quickly.

It is cheaper than writing your own loop and matches Turf's conventions, so an error thrown by collectionOf reads the same as one thrown by Turf core.

JavaScript
1function myClusterer(points) {
2  turf.collectionOf(points, 'Point', 'myClusterer');
3  // proceed safely — every feature is a Point
4}

FAQs

How do I install Turf.js to use this function?

Install npm install @turf/invariant and import import { collectionOf } from '@turf/invariant', or use turf.collectionOf on @turf/turf.

Does it check every feature?

Yes — on mismatched input it throws on the first non-matching Feature. For huge collections consider whether the O(n) validation overhead is worthwhile; for trusted inputs you may skip the check.

Can it validate MultiPolygon alongside Polygon?

No — the type string must match exactly. If you accept either, check them separately or pre-flatten the input.

Does turf.collectionOf return anything useful?

No — it only throws on mismatch. Think of it as assertCollectionOf. If it returns, the input is valid.