下面的代码在运行时运行良好,但是在编译时收到错误,除非我忽略错误,否则就无法生成生产代码。我不想这样做。
我无法投射到标记对象,因为标记似乎是一种方法。
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;
}
}
src / app / map / map.component.ts:265:49中的错误-错误TS2339:类型“ Layer”上不存在属性“ title”。
因此,Layer
不具有属性title
,但是具有MarkerOptions
。为Leaflet设置打字的方式,似乎他们希望您通过marker.options.title.
进行访问。但是,我不确定这是否可以按您期望的方式工作。
类型定义(请参见下面的链接)是在进行类型检查时确定什么是编译类型,什么是无效的。
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/leaflet/index.d.ts
您有几种选择。首先,您可以尝试找到一种从类型检查的角度有效的方法来访问title
属性。其次,您可以将其强制转换为any
以使其进行编译而不会出现错误/警告。前者比较好,但是如果您只是想使其工作,那么后者很好。
这里是强制转换为any
的示例:
if ( (this.markers[i] as any).title == pGuid ) { //compile time error
this.markers.splice( i, 1 );
//todo update server
break;
}