2

I am trying to extend the Marker class in leaflet.

I have read the tutorial on extending the class system and have managed to extend Marker with my desired functionality. However, I am unable to get everything working with no TypeScript errors.

I have my marker

const PhysicalSizeMarker = L.Marker.extend({ options: { width: 0, height: 0, }, ... }) 

and I have my factory as recommended by the tutorial

export function physicalSizeMarker(
  latlng: L.LatLngExpression,
  options: PhysicalSizeMarkerOptions,
) {
  return new PhysicalSizeMarker(latlng, options);
}

But the constructor of the factory has a type error:

Expected 0 arguments, but got 2.

I can make these errors go away by extending the Marker class in the usual JavaScript way and this seems to keep my added functionality working:

class PhysicalSizeMarker extends L.Marker {
  constructor(latlng: L.LatLngExpression, options: PhysicalSizeMarkerOptions) {
    super(latlng, options);
  }

This approach was recommended in this answer too https://stackoverflow.com/a/65692385/11451589

However, the leaflet documentation specifically says not to do that and instead use .extend

Does anyone know the correct approach to extending leaflet classes, such as markers, with TypeScript

1 Answer 1

1

When creating a class using the extend method, the constructor signature appears to be be unknown to TypeScript's type checking.

You could bypass TypeScript's type checking by doing something like this:

export function physicalSizeMarker(
    latlng: L.LatLngExpression, options: PhysicalSizeMarkerOptions) {

  return new (PhysicalSizeMarker as any)(latlng, options) as PhysicalSizeMarker;

}

I wrote an example here.

However, if there are better ways to do this, I would also be interested in knowing how.

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