0

Code below works fine at runtime, but receives an error at compile time which prevents me from building production code unless I ignore errors, which I don't want to do.

I'm unable to cast to a marker object as marker appears to be a method.

HTML

<div class="map-frame" leaflet [leafletOptions]="options"
    [leafletLayers]="markers" [leafletLayersControl]="layersControl"
    [(leafletCenter)]="center" (leafletMapReady)="onMapReady($event)"
    (leafletCenterChange)="onCenterChange($event)"
    (leafletMouseMove)="onMouseMove($event)"></div>

TypeScript

   markers: Layer[] = [];

       var markerObj: MarkerModel = {};

        markerObj.guid = this.utils.uuidv4();
        markerObj.iconUrl = pItem;
        markerObj.latitude = this.lat;
        markerObj.longitude = this.lng;
        const newMarker = marker(
            [markerObj.latitude, markerObj.longitude],
            {
                icon: icon( {
                    iconSize: [38, 38],
                    iconAnchor: [13, 13],
                    iconUrl: pItem
                } ),
                title: markerObj.guid
            }
        ).on( 'click', () => {
            this.zone.run(() => {
                this.onMarkerClick( markerObj );
            } );
        } );

        this.markers.push( newMarker );

            for ( var i = this.markers.length - 1; i >= 0; i-- ) {
                console.log( i, this.markers[i].title ); //compile time error
                if ( this.markers[i].title == pGuid ) { //compile time error
                    this.markers.splice( i, 1 );
                    //todo update server
                    break;
                }
            }

ERROR in src/app/map/map.component.ts:265:49 - error TS2339: Property 'title' does not exist on type 'Layer'.

1 Answers1

0

So, Layer does not have a property title, but MarkerOptions does. The way the typings were set up for Leaflet, it looks like they'd want you to access it via marker.options.title. But, I'm not sure if that'll work the way you expect.

The typings definition (see the link below) is what determines what is and is not valid at compile type when it'd doing type checking.

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/leaflet/index.d.ts

You have a couple options. First, you can try to find a way to access the title property in a way that is valid from a type checking perspective. Second, you could just cast to any to get it to compile without error/warning. The former is better, but the latter is fine if you just want to get it to work.

Here's an example of casting to any:

if ( (this.markers[i] as any).title == pGuid ) { //compile time error
      this.markers.splice( i, 1 );
      //todo update server
      break;
}
reblace
  • 4,115
  • 16
  • 16