Skip to content

Instantly share code, notes, and snippets.

@stepankuzmin
Last active April 29, 2020 15:48
Show Gist options
  • Save stepankuzmin/bb4c31e44596dc2e4fdb21f3d7e42337 to your computer and use it in GitHub Desktop.
Save stepankuzmin/bb4c31e44596dc2e4fdb21f3d7e42337 to your computer and use it in GitHub Desktop.
TypeScript Discriminated Union of ReturnTypes

TypeScript Discriminated Union of ReturnTypes

// DiscriminatedUnionOfReturnTypes.d.ts
type DiscriminatedUnionOfReturnTypes<T> =
  T[keyof T] extends (...args: any[]) => any ? ReturnType<T[keyof T]> : never;
// actionCreators.ts
import * as constants from './constants';

export const actionRequested = () => ({
  type: constants.ACTION_REQUESTED
}) as const;

export const actionRequestFailed = () => ({
  type: constants.ACTION_REQUEST_FAILED
}) as const;
// reducer.ts
import * as actionCreators from './actionCreators'

type Action = DiscriminatedUnionOfReturnTypes<typeof actionCreators>;

// type Action =
//   | { readonly type: 'ACTION_REQUESTED' }
//   | { readonly type: 'ACTION_REQUEST_FAILED' };
/* eslint-disable @typescript-eslint/no-explicit-any */
type DiscriminatedUnionOfReturnTypes<T> =
T[keyof T] extends (...args: any[]) => any ? ReturnType<T[keyof T]> : never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment