Equivalent of L.Class.include() with TypeScript

602 Views Asked by At

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 ?

1

There are 1 best solutions below

0
On BEST ANSWER

TL;DR : I have to use any unless they type Leaflet.Draw...

Okay so it was quite obvious in the end...

Because of Leaflet.Draw which has no types, I have to declare const L: any to avoid compilation errors when integrating the Leaflet.Draw plugin with Leaflet.

So obviously, when I call L.Rectangle, since L is of type any, I can't possibly use the typed include() method from Leaflet (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 new contains() method that I added since it is not linked to the actual L.Rectangle leaflet type.