In JavaScript (with Leaflet), I could implement some custom functionnalities using L.Class.include()
as written in the documentation :
Including more functionality in an existing class with L.Class.include() Adding new methods and options Changing some methods Using addInitHook to run extra constructor code.
This works :
L.Rectangle.include({
contains: function (markers: L.Marker[]) {
const markersContained: boolean[] = [];
markers.forEach(marker => {
console.log(marker);
markersContained.push(this.getBounds().contains(marker.getLatLng()));
})
return markersContained;
}
});
Now I'm trying to implement the same in an Angular4 Application with TypeScript, but the include()
function doesn't seem to be Typed in the @types/leaflet
The thing is that my code is in a .ts
file that is tailored for Leaflet.Draw
plugin, so I had to initialize the file this way :
declare const L: any;
import 'leaflet-draw/dist/leaflet.draw-src';
instead of the regular
import * as L from 'leaflet';
due to the fact that the Leaflet.Draw
plugin has no @types
, hence I can't import the regular leaflet types (Otherwise, new L.Control.Draw()
would make a compilation error).
This breaks at compilation time :
map.on(L.Draw.Event.CREATED, (geometry: L.LayerEvent) => {
const layer = geometry.layer;
drawnItems.addLayer(layer);
// Set an array containing all the markers
const markers = LeafletService.prototype.jsonToArray(layerGroup.getLayers());
// ===> Property 'contains' does not exist on type 'Layer'.
const result = geometry.layer.contains(markers);
console.log('result => ', result);
});
and obviously, this works if I set my geometry type as any
, but I'd like to use the L.LayerEvent
type if possible, and want to know how I could use the TypeScript syntax to use Leaflet include()
method correctly ?
TL;DR : I have to use
any
unless they typeLeaflet.Draw
...Okay so it was quite obvious in the end...
Because of
Leaflet.Draw
which has no types, I have todeclare const L: any
to avoid compilation errors when integrating theLeaflet.Draw
plugin withLeaflet
.So obviously, when I call
L.Rectangle
, since L is of typeany
, I can't possibly use the typedinclude()
method fromLeaflet
(I do use the actual method at runtime, but I can't make TypeScript aware of it for compilation time).It's only logical that the geometry returned from the
Leaflet.Draw
event doesn't know about the newcontains()
method that I added since it is not linked to the actualL.Rectangle
leaflet type.