Is it possible to obtain the return type of every function stored in an array?

I'm currently working with Redux and typesafe-actions, and I am trying to find a way to automatically generate types for the actions in my reducer. Specifically, I want to have code completion for each of the string literal values of the action.type property.

Here's my setup so far:

I've defined my actions using typesafe-actions as follows:

export const increment = (amount: number) => action("INCREMENT", { amount });
export const decrement = (amount: number) => action("DECREMENT", { amount });

To get the desired type, I use this line of code:

export type CounterActions = ReturnType<typeof increment | typeof decrement>;

However, maintaining this can be cumbersome because every time I add a new action, I need to remember to update the CounterActions type.

My solution is to store all action creator functions in an array like this:

export const actions = [
    (amount: number) => action("INCREMENT", { amount }),
    (amount: number) => action("DECREMENT", { amount })
]

Now, I am trying to figure out how to incorporate the contents of the actions array into the CounterActions type. Any suggestions on how to achieve this?

Answer №1

If you're using typesafe-actions, there's a convenient helper type called ActionType that can generate the necessary union for you based on a map object of actions. The simplest way to implement this is by creating a separate file with an import * statement. Here's an example:

import { ActionType } from 'typesafe-actions'
import * as counterActions from 'insert/filepath/here'

export type CounterActions = ActionType<typeof counterActions>;

In my own project, I've created a file specifically for RootAction, which combines all the actions used throughout the application. This file would look something like this:

import * as fooActions from './foo/actions'
import * as barActions from './bar/actions'
// and so on

export type RootAction = 
  ActionType<typeof fooActions>
  | ActionType<typeof barActions>
  // add more actions here as needed

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

Verification based on conditions for Angular reactive forms

I am currently learning Angular and working on creating a reactive form. Within my HTML table, I have generated controls by looping through the data. I am looking to add validation based on the following cases: Upon page load, the Save button should be ...

Anticipated the object to be a type of ScalarObservable, yet it turned out to be an

When working on my Angular project, I utilized Observables in a specific manner: getItem(id): Observable<Object> { return this.myApi.myMethod(...); // returns an Observable } Later, during unit testing, I successfully tested it like so: it(&apos ...

Type arguments cannot be accepted in untyped function calls.ts(2347)

My user schema in typescript includes the following interface: interface IUser{ name: string; email: string; password: string; isAdmin: boolean; } Check out the user schema below: const UserSchema = new Schema<IUser>( { name: { type ...

Using TypeScript to implement functional props in React applications

When passing functional props from a parent to a child component with typescript: import react, {Component} from 'react' import Child from './Child' //some type declaration class Parent extends Component<{IProps},{IState}> { stat ...

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

Angular 2 repeatedly pushes elements into an array during ngDoCheck

I need assistance with updating my 'filelistArray' array. It is currently being populated with duplicate items whenever content is available in the 'this.uploadCopy.queue' array, which happens multiple times. However, I want to update ...

Using React and TypeScript to Consume Context with Higher Order Components (HOC)

Trying to incorporate the example Consuming Context with a HOC from React's documentation (React 16.3) into TypeScript (2.8) has been quite challenging for me. Here is the snippet of code provided in the React manual: const ThemeContext = React.creat ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Show the outcome stored within the const statement in TypeScript

I am trying to display the outcome of this.contract.mint(amount, {value: this.state.tokenPrice.mul(amount)}) after awaiting it. I want to see the result. async mintTokens(amount: number): Promise<void> { try { let showRes = await this.c ...

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

How to disable typescript eslint notifications in the terminal for .js and .jsx files within a create-react-app project using VS Code

I'm currently in the process of transitioning from JavaScript to TypeScript within my create-react-app project. I am facing an issue where new ESLint TypeScript warnings are being flagged for my old .js and .jsx files, which is something I want to avo ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Derivation of the general function parameter

To provide a solution to this problem, let's consider the example below where a function is used. The function returns the same type that it accepts as the first argument: function sample<U>(argument: (details: U) => U) { return null; } ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

An issue has occurred: Unable to locate a supporting object 'No result' of type 'string'. NgFor is only compatible with binding to Iterables like Arrays

I am attempting to utilize this code to post data from a web service. service.ts public events(id: string): Observable<Events> { ...... return this.http.post(Api.getUrl(Api.URLS.events), body, { headers: headers }) .map((re ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...