Layers has a compilation error, but it runs fine at runtime

Even though the code works fine at runtime, I encounter an error during compile time which hinders the production build process, making it necessary to ignore errors, a practice I prefer to avoid.

The issue arises when trying to cast to a marker object that seems to be interpreted as a method.

Here is a snippet of the code:

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

And here is the TypeScript implementation:

   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 );

However, during compilation, I face the following error:

            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;
                }
            }

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

Answer №1

It appears that the Layer object does not include a title property, but the MarkerOptions object does. According to Leaflet's typings setup, it seems they intend for you to access it using marker.options.title.. However, there is uncertainty about whether this will function as expected.

The definitions in the typings file (linked below) determine what is considered valid during compile time type checking.

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

You have a couple of choices. One option is to find a way to access the title property in a manner that aligns with type checking requirements. Alternatively, you could simply cast to any to avoid compilation errors or warnings. The former approach is preferable, but the latter is acceptable if your priority is making it functional.

Below is 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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I incorporate a feature in my Angular application that allows users to switch between different view types, such as days, using JavaScript

Greetings, community! I am currently utilizing version 5 of the fullcalendar library from https://fullcalendar.io/ in my Angular 9 application. I have noticed that the calendar offers various options to change the view type as shown below: https://i.stac ...

Error message in Angular states that it is not possible to bind to 'formGroup' because it is not recognized as a property of 'form' within Angular

When trying to extract data from a form using formcontrol, everything seems to be working fine except for the [formcontrol] = "userForm" in the HTML. If I remove this part, the project runs smoothly. I have tried multiple tutorials but none of them seem ...

Unable to perform Undo function in monaco editor

Currently in my Angular 7 project, I have integrated the Monaco editor for coding purposes. One issue I am facing is that when I make a change to the code and then press ctrl+z to undo it, the previous code is successfully restored. However, if I change th ...

Is there a way for me to store the current router in a state for later use

I am currently working on implementing conditional styling with 2 different headers. My goal is to save the current router page into a state. Here's my code snippet: const [page, setPage] = useState("black"); const data = { page, setPage, ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

Tips on Including Service in Angular Testing Specification File with Jasmin/Karma

I'm a beginner when it comes to writing unit tests for Angular. I have a scenario where I need to inject a service into my controller file (.ts). How can I go about injecting the service file in the spec file? Below is the code snippet: app.componen ...

Is there a way to ensure that the observer.next(something) received the value before executing observer.complete()?

I have been working on an Angular app where I am using a resolver to preload data in the component. Below is the code for the resolver: resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): void { return Observable.create(observer => { ...

Struggling to obtain the Variable

Trying to send a POST request to my ESP8266 HTTP Server, I need to transmit 4 variables: onhour, offhour, onminute, offminute. These variables should be retrieved from a timepicker-component imported from "ng-bootstrap" Despite numerous attempts over the ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Error encountered in Next.js: TypeScript error with code ts(7031) - The binding element 'Component' is implicitly assigned the 'any' type

Converting my NextJS project to TypeScript presented a challenge for me. When working on my _app.tsx file, I came across a type error: 'pageProps' implicitly has an 'any' type. ts(7031). The error message likely resembled this image: ht ...

The angular2 error message indicating a property cannot be read if it is

Encountering an issue trying to utilize a method within an angular2 component. Here's the code snippet : import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AgGridModule } from &ap ...

How to update nested properties in Typescript using bracket notation

Imagine there is an interface and object with nested properties as shown below: interface Iobj { a: { a2:string }; b: string; } const obj: Iobj = { a:{ a2: "hello" } b: "world" }; Now let's say we have strings that ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? ...

Broadcasting TypeScript Data Structures via Socket.IO

In my Typescript code, I have created a basic User class as shown below: export class User { constructor(public id: string); } When I emit a message from my socket.io server, I include an instance of the User class like this: var user = new User(&ap ...

Using React MUI to implement a custom Theme attribute within a component

I have a CircularProgress element that I want to center, and to make the styling reusable, I decided to create a theme.d.ts file: import { Theme, ThemeOptions } from '@mui/material/styles' declare module '@mui/material/styles' { inte ...

Modifying a property in a nested layout through a page in Next.js 13

Currently, I am facing a challenge in updating the page title within a nested layout structure. app/docs/layout.tsx: export const DocsLayout = ({children}:{children: React.ReactNode}) => { return ( <> <header> ...

Testing Angular: How to Unit-test HttpErrorResponse with custom headers using HttpClientTestingModule

In the code snippet below, I am attempting to find a custom header on error: login(credentials: Credentials): Observable<any> { return this.http.post(loginUrl, credentials) .pipe( catchError((httpErrorResponse: HttpErrorRespo ...

The 'get' property in the class 'ToastInjector' cannot be assigned to the 'get' property in its base class 'Injector'

error TS2416: The property 'get' in the type 'ToastInjector' cannot be assigned to the same property in the base type 'Injector'. The type '(token: any, notFoundValue?: T, flags?: InjectFlags) => ToastPackage | T&apos ...

Incorporating TypeScript into an established Node.js Express project

I am keen on building a Node.js Express application using TypeScript. I have been watching several tutorials online to learn how to integrate TypeScript in Node.js, and fortunately, it is functioning as intended. However, the .ts files are currently bein ...