6

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?

1 Answer 1

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

4
  • This doesn't follow Leaflet plugin convention: "If you inherit one of the existing classes, make it a sub-property (L.TileLayer.Banana)." (leafletjs.com/examples/extending/extending-1-classes.html). I'd like to stick to the convention if possible.
    – solidau
    Commented Jan 13, 2021 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
    Commented Feb 8, 2021 at 2:13
  • @ghybs yeah, I ended up just doing it like this answer
    – solidau
    Commented Feb 9, 2021 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 Commented Nov 10, 2022 at 14:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.