Reputation: 4081
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?
Upvotes: 6
Views: 3587
Reputation: 259
OK, so I've been battling with this and I think I have it sorted:
Let's say I have this:
// MyExtendedMarker.ts
const MyExtendedMarker = Marker.extend({
foo: function() {
// do stuff
},
bar: "hello!"
})
I then created in my index.d.ts the following:
// index.d.ts
/// <reference types="leaflet" />
declare class MyExtendedMarker extends L.Marker {
foo(): void;
bar: string;
}
When I then went to use my created class, I had the correct classes. I even ended up changing the constructor to pass in my own type for options (which I also extended).
I deliberately avoided the new style of class MyExtendedMarker extends Marker
as that goes against how it's recommended by Leaflet as their classes are ES5 style classes.
Upvotes: 0
Reputation: 11338
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
}
}
Upvotes: 6