Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators.

A function has been crafted to accept a React dispatch: Dispatch<T> parameter:

const fetchProfileAction = actionCreator.async<void, Profile, any>('FETCH_PROFILE');
// AsyncActionCreators<Params = void, Result = Profile, Error = any>;


type AsyncDispatch<A extends AsyncActionCreators<Params, Result, Error>, Params, Result, Error> = Dispatch<
  ReturnType<A['started'] | A['done'] | A['failed']>
>;

export const fetchProfile = (
  dispatch: AsyncDispatch<typeof fetchProfileAction, void, Profile, any>,
) => async () => {
  dispatch(fetchProfileAction.started());

  try {
    dispatch(fetchProfileAction.done({ result: (await api.get<Profile>('/profile')).data }));
  } catch (e) {
    dispatch(fetchProfileAction.failed(e));
  }
};

The current challenge lies in having to manually specify the types within fetchProfileAction:

AsyncDispatch<typeof fetchProfileAction, void, Profile, any>

Is there a way to simplify this and achieve something like

AsyncDispatch<typeof fetchProfileAction>
, automatically resolving Params, Result, Error types of AsyncActionCreators?

Answer №1

If you're looking to take advantage of type inference within conditional types, check out this resource on TypeScript's website:

type AsyncDispatch<A> = A extends AsyncActionCreators<infer Params, infer Result, infer Error>
    ? Dispatch<ReturnType<A['started'] | A['done'] | A['failed']>>
    : never;

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

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

Form containing a pair of buttons

I am attempting to design multiple forms with two buttons, each of which will submit the form to a different script. One button will use ajax for submission, while the other will simply submit the form without ajax. <?php foreach($objects as $object) : ...

Converting JavaScript functions to Java remote method interfaces

Experience: A while back, I was involved in developing a Java Server-Client application for building automation purposes. Initially, we used Java RMI to connect the server and client but soon realized that utilizing JavaScript for the client side would be ...

Switch the checkbox to a selection option

Is there a way to switch the selection method from checkboxes to a dropdown menu? $("input[name=koleso]:first").prop("checked", true); $('body').on('click', '.koleso label', function (e) { koles ...

Stop JQuery from executing when an error is caught

Once the document is ready, I have configured: $.ajaxSetup({ "error": function (XMLHttpRequest, textStatus, errorThrown) { if(XMLHttpRequest.status == 403) { display_modal( 'Please login to continue.', &ap ...

Appending an item to an array in TypeScript

I'm feeling lost. I'm attempting to insert new objects into an array in TypeScript, but I encountered an error. My interface includes a function, and I'm puzzled. Can anyone offer guidance? interface Videos{ title: string; descriptio ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

Navigating the landscape of asynchronous asset loading can present challenges. Attempting to access assets immediately may result in receiving

I have encountered an issue while trying to load my assets into an array using a function called LoadJSON(). This function utilizes THREE.ObjectLoader() to load JSON files. The problem arises when I attempt to access the members of the array immediately af ...

Ensure to utilize object identities while employing QUnit.deepEqual() with an array

Let's set the scene: I have a function that returns an array of objects. These objects do not have any enumerable properties, but are sourced from a common cache or store. In my test cases, I want to verify if the contents of the returned array are a ...

"Dealing with an unspecified number of fields in an ExtJS data model

I have a data model that is designed to accommodate various incoming data by keeping it generic and allowing for the addition of multiple meta data tags to my project. How can I effectively map these data fields to the Model or access them in the array w ...

Guide to building a straightforward line graph using JSON data from a server

When I retrieve price change data from an API endpoint using axios, the response I receive is in the following format: 0: (2) [1639382650242, 48759.49757943229] 1: (2) [1639386250855, 49131.24712464529] 2: (2) [1639389730718, 48952.65930253478] 3: (2) [163 ...

"Learn to easily create a button within a table using the powerful functionality of the dataTable

I need to add a button to each row in a table. I managed to achieve this with the code below, but there's a problem - every time I switch between pages, the button keeps getting added again and again. It seems like the button is generated multiple tim ...

how to use jQuery to sort appended data

I have a loop that retrieves data from the server in descending order, but when I use "append()" to add the data, it doesn't maintain the correct sorting. For instance, the first row shows up in the second position. Is there a way to append the data ...

Preventing the addition of hash tags to the URL by the anything slider

Why does the Anything Slider add hash tags like #&panel1-1 to the end of the URL? I attempted using hashtags:false but it was unsuccessful. Are there alternative methods to prevent it from creating these hashtags? ...

Geolocation plugin in Ionic encountered an issue: "Geolocation provider not found"

I've been working on implementing geolocation in my ionic2 hello world project, and I successfully added the ionic plugin called "Geolocation" by following the instructions on the official website. After running these two commands: $ ionic plugin add ...

"Injecting the value of a jQuery variable into a PHP variable

<script type="text/javascript"> $(document).ready(function(){ $("#t_select").change(function(){ var table_name = $("#t_select").val(); $.ajax({ type: 'POST', ...

How do I handle the error "Uncaught TypeError: Cannot read property 'func' of undefined in React JS

Hey there, I've encountered an issue while setting up a date picker on my project. I tried using these resources: https://github.com/Eonasdan/bootstrap-datetimepicker Would appreciate any help! https://codesandbox.io/s/18941xp52l render() { ...

Browsing an array of objects to extract targeted information

I'm in the process of developing a node express angular tool for analyzing Twitter statuses and I am facing the challenge of extracting text from it and combining it into a single long string for future use. This is how I am attempting to retrieve us ...

I am developing a JWT authentication and authorization service for my Angular application. However, I am running into issues when trying to implement observables

I have created a user class and required interfaces as outlined below: user.ts import { Role } from '../auth/auth.enum' export interface IUser { _id: string email: string name: IName picture: string role: Role | string userStatus: b ...

Exploring the object structure received from AngularFire

Here is the Firebase query that I am running: var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status'); data = $firebaseObject(ref); console.dir(data); The object that I receive looks like this: d ...