typescriptleafletreact-leaflet

How to type iconCreateFunction from MarkerClusterGroup


I have created a small test using MarkerClusterGroup from react-leaflet-cluster.

Although it works, I have a hard time making all the types work in TypeScript:

<MarkerClusterGroup
    iconCreateFunction={createCustomClusterIcon}>
</MarkerClusterGroup>

The callback function looks like this:

const createCustomClusterIcon = (cluster) => {
   const markers = cluster.getAllChildMarkers();
   // ...
}

So, the problem I have is typing the cluster property. The only types that I was able to give to cluster was any and { getChildCount: () => string }. But what should this type be?


Solution

  • The iconCreateFunction prop mirrors the same named option from Leaflet.markercluster plugin.

    Although not explicitly described, the callback is passed the MarkerCluster instance. You can get its type in L from "leaflet" after you have also done import "leaflet.markercluster" so that it performs the side effect of Leaflet module augmentation:

    import L from "leaflet";
    import "leaflet.markercluster"; // Import for side effect of Leaflet module augmentation
    import MarkerClusterGroup from "react-leaflet-cluster";
    
    const createCustomClusterIcon = (cluster: L.MarkerCluster) => {
        const markers = cluster.getAllChildMarkers();
        // ...
        return L.icon({ iconUrl: "" })
    }
    
    () => (
        <MarkerClusterGroup
            iconCreateFunction={createCustomClusterIcon} // Okay
        >
            (markers...)
        </MarkerClusterGroup>
    );
    

    Playground Link