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?
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
2
To derive the cluster type you can infer the params used by the default export
try using the following code
import cluster from "react-leaflet-cluster";
type InferIt<T, V extends "RT" | "P" | "B"> = T extends (
...args: infer P
) => infer RT | Promise<infer RT> | PromiseLike<infer RT> | Awaited<infer RT>
? V extends "B"
? { readonly params: P; readonly returnType: RT }
: V extends "RT"
? RT
: V extends "P"
? P
: T
: T;
type ClusterInferred = InferIt<typeof cluster, "P">['0'];
The InferIt
type above has a union of three options: (1) “RT” -> infer the ReturnType; (2) “P” -> infer the Params; (3) “B” -> infer Both which has the shape of { readonly params: P; readonly returnType: RT }
link to the playground
screenshot of clusters type being inferred
Note: you may need to configure settings>plugins in the typescript playground to support these packages. Here is a screenshot of the npm modules I added to the playground to provide this solution
1