Is it possible in Typescript to pass method signature with parameters as an argument to another method?

I am working on a React app where I have separated the actions into a different file from the service methods

hoplite.actions.ts

export const fetchBattleResult = createAsyncThunk<Result>(
'battle/fetchBattleResult',
HopliteService.battleResult,
);

hoplite.service.ts

In my service file, I have an async method called battleResult that takes in a parameter of type Battle and returns a Promise of type Result:
const battleResult = async (item: Battle): Promise<Result> =>
  await fetch(`${API_URL}/battle`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(item),
  }).then((response) => response.json());

When trying to send the signature of battleResult, VSCode is showing me an error regarding incompatible types for the parameters. It seems like it's not recognizing the param being passed.

The error message states: 'Argument of type '(item: Battle) => Promise<Result>' is not assignable to parameter of type 'AsyncThunkPayloadCreator<Result, void, {}>'.
  Types of parameters 'item' and 'arg' are incompatible.
    Type 'void' is not assignable to type 'Battle'.ts(2345)

I would greatly appreciate any suggestions on how to correctly specify or include the parameters in the signature when sending it. Thank you!

Answer №1

When you specifically define the first generic argument, the second one defaults to a fallback value of void. To avoid errors, it's important to either provide all arguments or none and let TypeScript infer the types. Mixing explicit and inferred type arguments is not supported.

Both approaches are valid.

export const fetchBattleResult = createAsyncThunk(
  "battle/fetchBattleResult",
  HopliteService.battleResult
);

or

export const fetchBattleResult = createAsyncThunk<Result, Battle>(
  "battle/fetchBattleResult",
  HopliteService.battleResult
);

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

Leverage tsconfig.json for TypeScript compilation in Vim using the Syntastic plugin

How can I configure the syntastic plugin in vim to provide live error checking for TypeScript files using tsc? Currently, even though I have tsc set up in vim, it doesn't seem to be using the closest parent's tsconfig.json file for configuration. ...

Group Hover by StyleX

I recently experimented with the innovative StyleX library and encountered a particular challenge. Can a group hover effect be achieved for a component solely using this library? For instance, let's assume we have the following component in Tailwind ...

What is preventing me from setting the User object to null in my Angular application?

Currently, I am working on a project in Angular and encountering a specific issue. In my service class, the structure looks like this: export class AuthService { authchange: new Subject<boolean>(); private user: User; registerUser(authD ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

Ways to sign up for the activeDate variable in MatCalendar so you can display the month and year labels of the current active date in the

As a newcomer to Angular, I am working on creating a datepicker with a customized header. I have successfully passed a custom header for the mat-calendar component. Reference: https://material.angular.io/components/datepicker/overview#customizing-the-calen ...

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Leveraging vue-devtools in combination with the composition-api while implementing a render function (such as JSX)

Ever since I made the transition to utilizing the composition-api and incorporating a render function (primarily leveraging JSX with TypeScript for type safety within the template), I've encountered an issue where vue-devtools cannot inspect the compu ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

Angular 2: Integrating a service into a class

I am working on an Angular class that represents a shape. My goal is to be able to create multiple instances of this class using a constructor. The constructor requires several arguments that define the properties of the shape. constructor(public center: ...

What is the best way to obtain the value of a nested formBuilder group?

Currently, my nested form is structured like this: this.form = this.formBuilder.group({ user: this.formBuilder.group({ id: ['', Validators.required], name: ['', Validators.required], phone: ['' ...

Comparing JSON import methods: HTTP vs require

I discovered two methods for importing local json files into my code. Using angulars http get. This method is well-known for loading json input. It provides the flexibility to easily switch between remote and local json files. Typescript require Anot ...

An issue was encountered in the node_modules folder while attempting to access the 'Exclude' name in the lodash collection file. The error message reads: (1783,24): error TS2304: Cannot

When attempting to execute the ng serve command, I encountered an error. See below for more details. ERROR in node_modules/@types/lodash/common/collection.d.ts(1783,24): error TS2304: Cannot find name 'Exclude'. ... (error list continued) .. ...

Flex-Layout in Angular - The Ultimate Combination

Recently, I decided to delve into Angular and the Flex-Layout framework. After installing flex-layout through npm, I proceeded to import it in my app.module.ts file like so: import { FlexLayoutModule } from '@angular/flex-layout'; imports: [ Fl ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

Display a dynamic array within an Angular2 view

I have a dynamic array that I need to display in the view of a component whenever items are added or removed from it. The array is displayed using the ngOnInit() method in my App Component (ts): import { Component, OnInit } from '@angular/core' ...

Struggling to locate the module 'firebase-admin/app' - Tips for resolving this issue?

While working with Typescript and firebase-admin for firebase cloud functions, I encountered the error message "Cannot find module 'firebase-admin/app'" when compiling the code with TS. Tried solutions: Reinstalling Dependency Deleting node_modu ...

What is the best approach for implementing recursion within a foreach loop in TypeScript?

Problem Situation I am attempting to develop a customized typewriting effect similar to the one demonstrated here with a 100ms delay using Angular. The TypeScript code I have written for this purpose is as follows: private arr: string[] = ["Lead Dev ...

Something went wrong trying to retrieve the compiled source code of https://deno.land/[email protected]/path/mod.ts. It seems the system is unable to locate the specified path. (os error 3)

Upon executing my main.ts script using deno, I encounter the following error message: error: Failed to retrieve compiled source code from https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcccbdbff8f918a86918f"& ...

Utilizing TypeScript to invoke a method via an index signature

Here is a snippet of my code, where I am attempting to call a method using an indexed signature. It functions properly when the function name is manually added, but how can I call it using object notation for dynamic calls? createFormControl(formControls: ...