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

rearranging the sequence of buttons using JavaScript

I am faced with the challenge of making a series of buttons draggable and droppable within a parent div without using any external libraries at the request of the client. Although I could have easily accomplished this task with jQuery, it's an opportu ...

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

What strategies can I use to control the DOM within the onScroll event in ReactJS?

I am currently working on implementing an arrow-up button that should be hidden when I am at the top of my page and displayed once I scroll further down. However, I am facing issues with manipulating the DOM inside my handleScroll function to achieve this. ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

Issue with Angular/Jasmine: Undefined property 'pipe' not readable

I have been struggling to resolve a problem with Angular 9, Jasmine, and RxJS without much success. While my unit tests run successfully in Jasmine, there are certain lines of code that do not get executed. Despite scouring multiple posts for assistance, ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Perform an AJAX request within a condition prior to executing the subsequent AJAX request

Within my database, I have two tables. When the submit button is pressed, I aim to insert a new trader into the trader table and retrieve the ID using laravel 5.2 by utilizing post ajax under certain conditions. Then, execute another post ajax for invoic ...

The code stored in Github differs from the code deployed on the production server

I recently took over a project that had been outsourced to a web development company in the past, and it's built on the MEAN stack. After struggling to get the code from the Github repository to work properly, I decided to download the code directly ...

Display the div only when the time variable reaches zero

I want to display a div when the difference between the time imported from the database and the current time is 0. How can I achieve this? Here is the code snippet: while ($row = mysqli_fetch_array($result)) { echo "<div class='alert' id= ...

Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] To ensure uniqueness, I implemented a c ...

Setting up the karma ng-html2js preprocessor to locate my templates within a specific folder

Currently, I am facing an issue where I need to set the templateUrl: "partials/my-directive.html" However, I find that I have to use templateUrl: "app/partials/my-directive.html for it to be loaded by Karma. This is how my folder structure looks like (fo ...

Removing JSON data with JavaScript

Currently, I am working on developing a custom discord bot for a server that I share with some friends. The bot includes a warn system and level system, and I have successfully implemented JavaScript to write data to an external JSON file. { "othe ...

Utilizing Interface Merging: Determining the Appropriate Instance Type for Field Types

I am in need of writing a definition file for an external library. I have augmented a class using interface merging and there are situations where a field of the library class is of the same type as the instance itself. Here is a snippet of demo code: // ...

How can you display a border around a <td> element in an HTML table only when it contains data, using jQuery or JavaScript?

My HTML table consists of the following structure: <table class="table table-bordered"> <thead> <tr> <th>Tag</th> <th>Time Code</th> </tr> </thea ...

What is the best way to retrieve comprehensive information from an API?

I have a task to complete - I need to retrieve data from the Pokemon API and display it on a website. This includes showing the name, HP, attack, defense stats of a Pokemon, as well as the Pokemon it evolves into. The challenge I'm facing is obtaining ...

An issue has occurred: it seems that the property cannot be accessed because `this.child` is undefined

Is there a way to call the function "initMap" that is defined in the child component "UpdatePinComponent", from the parent component named "ApiaryComponent"? Below is a snippet of the TypeScript code from the parent component: import { AfterViewInit, Compo ...

After making the request, $.getJSON initially comes back as undefined but eventually delivers

I found myself in a sticky situation. I was working on coding a Wikipedia search tool for a personal project, but encountered a small glitch. When a user types a word into the search bar, it gets stored in the data parameter of $.getJSON. The response then ...

Tips for resizing user-uploaded images to fit the required dimensions outlined in the design draft using CSS or JavaScript

Hey everyone! I'm facing an issue but my English isn't great. I'll do my best to explain it thoroughly, and if anything is unclear, please feel free to let me know! So here's the problem: today there's a block for users to upload p ...

Issue with type narrowing and `Extract` helper unexpectedly causing type error in a generic type interaction

I can't seem to figure out the issue at hand. There is a straightforward tagged union in my code: type MyUnion = | { tag: "Foo"; field: string; } | { tag: "Bar"; } | null; Now, there's this generic function tha ...