Avoiding Any Errors When Using TypeScript Array Map with Objects

Currently in the process of upgrading my Angular project to version 13 within a new workspace. While transferring code, I encountered a typescript-eslint error that has me stumped.

The previous working code looked like this:

interface IConfigurationSetting {
  category?: string,
  key?: string,
  value?: string | number,
  message?: string
}

export class ConfigurationSetting implements IConfigurationSetting {
  category: string;
  key: string;
  value: string | number;
  message: string;

  constructor(options: IConfigurationSetting = {}) {
    this.category = options.category || '';
    this.key = options.key || '';
    this.value = options.value || '';
    this.message = options.message || '';
  }
}

export class ConfigurationSettingsGroup {
  settings: ConfigurationSetting[];
  errors: string[];

  constructor(options: {
    settings?: ConfigurationSetting[],
    errors?: string[]
  } = {}) {
    this.settings = (options.settings || []).map(setting => new ConfigurationSetting(setting));
    this.errors = options.errors || [];
  }
}

After running the VSC eslint check with the new setup, an error is now triggered for the setting parameter in the new ConfigurationSetting(setting) call - "Unsafe argument of type 'any' assigned to a parameter of type 'IConfigurationSetting'".

I structured my classes in this way to ensure that properties of complex objects or arrays have necessary defaults. Is it still acceptable to map arrays of complex objects as shown above? If yes, how can I resolve this unsafe rule violation without completely disabling it? Alternatively, is there a more effective method for mapping arrays of complex object types?

UPDATE: I made a modification that eliminated the "Unsafe argument of type 'any' assigned to a parameter of type 'IConfigurationSetting'" error:

this.settings = <ConfigurationSetting[]>(options.settings || []).map((setting: ConfigurationSetting) => new ConfigurationSetting(setting));

Despite this change, I am still encountering a typescript-eslint error:

Unsafe call of an `any' typed value. eslint(@typescript-eslint/no-unsafe-call)

This error specifically occurs at (options.settings || []).map. Any suggestions on resolving this issue would be greatly appreciated.

Answer №1

It appears that the warning from the linter is due to implicit type conversions in your code snippet.

The specific areas causing the issue are:

constructor(options: IConfigurationSetting = {}) {
                                         //   ^ Here, this has an "any" data type
this.settings = (options.settings || []).ma...
                                  //  ^ Here, this has an "any[]" data type

To address this, you can perform some explicit casting:

constructor(options: IConfigurationSetting = <IConfigurationSetting>{}) {
...

this.settings = (options.settings || <ConfigurationSetting[]>[]).ma...

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

Direct to another route in Angular 2 if the user is already authenticated

Looking at my route setup, it's structured like this: const routes: Routes = [ { path: '', redirectTo: '/login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'dashboard& ...

Create a balanced mixture of 1s and 0s in an array using a random generator

I am faced with a challenge involving an array containing 20 members, from which I need to extract single values sequentially. For testing purposes, the current contents of the array are as follows: int PhaseTesting1Array[20] = { 1,0,1,0,1,0,1,0,1,0,1,0,1 ...

arranges the objects in the array based on the attribute of the child objects within the array

Apologies for my limited English proficiency, I hope everyone can follow along. I am dealing with an array: const arr=[ { name:"c", pay:[{ name:"c", date: "2020-10-02" },{ name:"cc1" ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

Returning an array-filled marshaling structure

The structure in the C++ code is defined as follows: typedef struct _a astruct; struct _a { BYTE fi, Sec, *D, *IIV, PV; bool Visited; }; There is also a function that utilizes this structure: astruct DoPDC(string *InitialData); To use this func ...

What is the best way to incorporate a Promise into this function?

Looking to convert this Typescript method into one that returns a Promise, but only once the this.user.currentCourseId = student.currentCourseId; line has been executed. Is it feasible to achieve this? public getUserData() { ... this.authState.a ...

Send an array to a function with specified criteria

My current code successfully splits an array, but I need to pass a value when the array condition is met. For example, here is how the value is split into an array: var myArr = val.split(/(\s+)/); If the array in position 2 is empty, I need to use ...

Retrieve an item from an array by utilizing the `array.some()` method instead of just getting

I am currently attempting to utilize the array.some function to traverse through a dataset and retrieve my field when the specified condition is met. However, what I'm experiencing is that instead of obtaining the variable (which holds details to an ...

Using an exported function with parameters as a filtering mechanism for the material datepicker

I am currently facing an issue while trying to set a const exported function in a material datepicker filter with parameters. When I try to set the parameters in my component, the function gets executed and returns the result (a boolean) instead of simply ...

Create the HTTP POST request body using an object in readiness for submission

When sending the body of an http post request in Angular, I typically use the following approach: let requestBody: String = ""; //dataObject is the object containing form values to send for (let key in dataObject) { if (dataObject[key]) { ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

Invoke a shared function within multiple component HTML files when an onchange event is triggered by a universal service

Hello there, I am currently working with angular 11. In my project, I have three components named C1, C2, and C3. These components do not have a parent-child relationship but they all share a common method called F1. Right now, F1 is declared in each compo ...

Encountering a TypeScript error while generating a sitemap in an array within Next.js 14

Recently, I created a sitemap.tsx file within the app router in NextJS 14. However, I encountered an issue when attempting to create an array of routers as shown below: const contacts = NavContacts?.filter((val) => { if ( !val.name.inc ...

Consolidate the indexes of arrays into a single object

Is there a way to combine array indexes into one object using a key-value pair format, like {authors[i]: quotes[i]} in my example? If you'd like to review the code, please visit my Codepen: http://codepen.io/anon/pen/Ndezeo Thank you. ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

When working on one of my subdomains, I require the ability to distribute cookies between the two

Currently, I am involved in a project that utilizes a sub-domain under a parent domain called "my-project.parent.com", which unfortunately I do not have access to. Additionally, there is another project operating under the main domain "parent.com" with t ...

Angular: Resetting a conditional form control with matching name

Currently, my code looks something like this: <input *ngIf="a" #autocomplete formControl="myControl"> <input *ngIf="!a" #autocomplete formControl="myControl"> These inputs have different attributes depen ...

The global CSS styles in Angular are not being applied to other components as expected

Currently utilizing Angular v10, I have a set of CSS styles that are meant to be used across the entire application. To achieve this, I added them to our global styles.css file. However, I'm encountering an issue where the CSS is not being applied to ...

Is it possible to maintain the scroll position of a PrimeNG table when updating the data?

I've encountered a challenge while working on a project involving PrimeNG 12 tables with Angular 12. The issue lies in Angular's change detection mechanism and updating table data, specifically in preventing a PrimeNG p-table from scrolling back ...

Using an Object as a Key in Maps in Typescript

I had the intention of creating a Map object in Typescript where an object serves as the key and a number is the value. I attempted to define the map object in the following manner: myMap: Map<MyObj,number>; myObj: MyObj; However, when I tried to a ...