5

I'm working on a project with Typescript and Leaflet.

The documented (JS) way to extend the leaflet marker is like this:

L.Marker.Foo = L.Marker.extend({...});

However, Typescript complains:

Property 'Foo' does not exist on type 'typeof Marker'.

How can I change it so there are no compile errors?

solidau
  • 4,021
  • 3
  • 24
  • 45

1 Answers1

6

Extend the Marker like:

 export class TSMarker extends L.Marker {
        options: L.MarkerOptions

        constructor(latLng: LatLngExpression, options?: L.MarkerOptions) {
            super(latLng, options)
        }

        greet(): this {
            this.bindPopup("Hello! TSX here!")
            return this
        }

    }

Src

Falke Design
  • 10,635
  • 3
  • 15
  • 30
  • This doesn't follow Leaflet plugin convention: "If you inherit one of the existing classes, make it a sub-property (L.TileLayer.Banana)." (https://leafletjs.com/examples/extending/extending-1-classes.html). I'd like to stick to the convention if possible. – solidau Jan 13 '21 at 19:54
  • @solidau I know very well this Leaflet convention, which dates back to when scope pollution was an issue, but it does not play well with TypeScript. In your case, you would have to manually extend the Leaflet namespace, just to ged rid of this TS compiler complaint. – ghybs Feb 08 '21 at 02:13
  • @ghybs yeah, I ended up just doing it like this answer – solidau Feb 09 '21 at 19:18
  • Something seems wrong with the suggested approach... Leaflet does not use standard ES6/typescript classes, they use a custom in-house class system. Why the type definitions are made using classes? Beats me... But doing the suggested approach here does not leverage any of the class system that leaflet uses – Etienne Martel Nov 10 '22 at 14:58