The type 'any' cannot be assigned to the parameter type 'never' in this argument.ts

I received a warning:

Argument of type 'any' is not assignable to parameter of type 'never'.ts(2345) Object is of type 'unknown'.ts(2571)

Here is my request body:

{"A":[{"filter":[{"a":"a"}]},{"group":[{"a":"a"}]}],"B":[{"filter":[{"a":"a"}]},{"group":[{"a":"a"}]}], ...}

Below is my script :

var a = Object.entries(body).reduce((acc, [key, value]) => {                                                                    
 acc.filter.push(...value[0].filter);                                                                    
 acc.group.push(...value[1].group);
 return acc;
}, {filter: <any>[], group: <any>[]});

The warning is triggered by ...value[0].filter and ...value[1].group, possibly due to the variable type unknown assigned to key and value within [key, value]

Appreciate your help

Answer №1

To start off, we can utilize a const assertion to ensure that the compiler recognizes that each property of body is a tuple where the first element contains a filter property and the second element contains a group property. This is crucial for the safety of your code when accessing value[0].filter and value[1].group:

const body = {
  A: [{ filter: [{ a: "a" }] }, { group: [{ a: "a" }] }],
  B: [{ filter: [{ a: "a" }] }, { group: [{ a: "a" }] }]
} as const;

The issue at hand is that the compiler interprets your call to

array.reduce(callback, initialAccumulator)
with an initialAccumulator object containing empty arrays, leading it to believe that these arrays will always have no actual elements (e.g., Array<never>). Therefore, when you attempt to add elements to such an array, it raises an error due to the mismatch in types. To address this, you need to provide a method to indicate or confirm that the accumulator will be storing an array of elements. Here's how you can achieve this:

interface Filter { a: string };
interface Group { a: string };
interface FiltersAndGroups {
  filter: Filter[];
  group: Group[];
}

// explicitly specify FiltersAndGroups as the accumulator type:     
var a = Object.entries(body).reduce<FiltersAndGroups>(
  (acc, [key, value]) => {
    acc.filter.push(...value[0].filter);
    acc.group.push(...value[1].group);
    return acc;
  },
  { filter: [], group: [] } 
)

In this case, the types Filter, Group, and FiltersAndGroups are chosen to represent the accumulator type, and the generic parameter of the reduce() method is manually specified to prevent the erroneous inference of [] as an array of never[]. By following this approach, the code should function without any errors. Best of luck with your implementation!

Link to code

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

Why isn't my component calling the service.ts file?

In my Angular project, I am working on a home component that contains a specific method. This method is defined in a service file called service.ts and imported into the homecomponent.ts file. The method is named filterClicked with a condition within the s ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

Having trouble directing my attention towards a Mat card when using viewchildren in Angular

My current challenge is trying to focus on a specific card from a list of mat cards Despite my efforts, I keep encountering an error that reads: Cannot read property 'focus' of undefined Access the code on StackBlitz The desired functionali ...

Angular form requests can utilize the Spring Security Jwt Token to allow all options methods

Despite checking numerous sources online, I am facing a persistent issue with my Angular application. The problem arises when using HttpClient along with an Angular interceptor to set headers for authentication in my Java Rest API using JWT tokens. The int ...

Generate a collection of items through replication

Develop a function that takes specific input and generates an array of objects with a length of 10 by incrementing the ID of each duplicate object. The first object in the output array should have "visible" set to true, while all others should have it set ...

Can you use getters and setters in a TypeScript declaration file?

I am facing an issue with a declaration file for the openUi framework. The framework utilizes a get<propname>() and set<propname>(var) syntax for its properties. In traditional JavaScript, the setup would look like this: sap.ui.getCore().atta ...

Change Json data into a TypeScript class [ts]

I have the following JSON data: {"mapData":{"test":"success","publicKey":""},"statusCode":200,"message":null} How can I convert this JSON to a TypeScript class? The mapData contains anonymous values: It may be {"test":"success","publicKey":""} Or it m ...

Steps to converting an enum or literal

Hey there, I'm relatively new to working with TypeScript and I've been experimenting with transforming enums/literals using functions. For instance, creating a capitalize function that capitalizes the first letter of a string. (e.g., mapping typ ...

The issue of Eslint flagging a no-unused-vars error when actually using an interface in a

Currently, I'm working with Vue along with Vue CLI and Typescript. I have imported an interface from a Vuex file and utilized it for type annotation in mapState. However, I am encountering an error flagged by eslint. 'State' is defined ...

Exploring how NestJS can serialize bigint parameters within DTOs

I have data transfer objects (DTOs) with parameters that are of type bigint. However, when I receive these DTOs, the parameters always have a type of string. Here is an example: @Get("") async foo(@Query() query: Foo) { console.log(typeof Foo ...

How can I retrieve a certain type of object property in TypeScript?

Imagine having a collection of flags stored in an object like the example below: type Flags = { flag1: string, flag2: string, flag3: boolean, flag4: number } // const myFlags: Flags = { // flag1: 'value 1', // flag2: 'value 1&ap ...

The NestJS Backend is always being asked by Grafana to access the /api/live/ws endpoint

After successfully setting up Grafana and Grafana Loki with my NestJS Backend, everything seemed to be working fine. However, I started getting a 404 error from my NestJS because Grafana was requesting the /api/live/ws route. Is there a way to disable thi ...

The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be ...

How can you initialize Boostrap components or Materialize css in Angular 5 without using any external libraries?

I am a beginner exploring the world of Typescript and Angular. I am curious about how to initialize Bootstrap elements in an Angular-friendly manner without using the ngx-Bootstrap wrapper. For instance, if I wish to initiate a Bootstrap carousel. As per ...

Solving commitments through a series of actions

Can someone please explain why when resolving promises in a loop, accessing the loop variable is necessary for it to work correctly? Here's an example where logging occurs 5 times: for (let i = 0; i < 5; i++) { this.getData() .then(() ...

Navigating the way: Directing all TypeScript transpiled files to the build folder

I am currently working on a project using Angular2/Typescript, and I have the tsconfig.js file below: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "target": "es5", "sourceMap": true, ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

Updating a string's value in Angular based on user input

I am currently developing a custom offer letter template that will dynamically update key data points such as Name, Address, Role, Salary, etc based on the selected candidate from a list. The dynamic data points will be enclosed within <<>> in ...

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...