Skip to content

Instantly share code, notes, and snippets.

@smcatala
Created August 10, 2019 22:37
Show Gist options
  • Save smcatala/31ccd05b355b409a4ad4260fbe82cba8 to your computer and use it in GitHub Desktop.
Save smcatala/31ccd05b355b409a4ad4260fbe82cba8 to your computer and use it in GitHub Desktop.
Strong typing of Redux actions and action-factories with Typescript conditional types: minimal boilerplate, helpful code-completion

Typescript conditional types provide a new approach to proper typing of Redux actions and action-factories.

Countless blogs and libraries have been written on this subject, trying to work around the limitations of the default type definitions of Redux. However, these numerous attempts to reduce boilerplate and to improve type cohesion unfortunately remained unsatisfactory without conditional types.

Working through our (enormous) backlog of unsorted TypeScript "Suggestions" and it's remarkable how many of them are solved by conditional types. -- Ryan Cavanaugh, TypeScript maintainer

Redux action types are definitely greatly improved if not solved by conditional types:

/**
 * @license MIT
 * @author Stephane M. Catala <[email protected]>
 *
 * Copyright (C) 2019, Stephane M. Catala <[email protected]>
 *
 * Permission is hereby granted, free of charge,
 * to any person obtaining a copy of this software
 * and associated documentation files (the "Software"),
 * to deal in the Software without restriction,
 * including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice
 * shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

export interface Action<T extends string = string, P = any> {
  readonly type: T
  readonly payload?: P
}
// helpers based on conditional types
export type ActionType<A> = A extends Action<infer T, any> ? T : never
export type ActionPayload<A, T extends string = any> = A extends Action<T, infer P> ? P : never

// action-factories
export type ActionFactories<A extends Action> = {
  [T in ActionType<A>]: ActionFactory<Action<T, ActionPayload<A, T>>>
}
export type ActionFactory<A extends Action> = {
  (payload?: ActionPayload<A>): Action<ActionType<A>, ActionPayload<A>>
}

export function createActionFactories<A extends Action> (
  ...types: ActionType<A>[]
): ActionFactories<A> {
  const actions = Object.create(null)
  for (const type of types) {
    actions[type] = createActionFactory<A>(type)
  }
  return actions
}

export function createActionFactory<A extends Action> (
  type: ActionType<A>
): ActionFactory<A> {
  return payload => ({ type, payload } as const)
}

example usage:

interface Todo {
  id: string
  objective: string
  done?: boolean
}

type AddTodo = Action<'ADD_TODO',Todo>
type ToggleTodo = Action<'TOGGLE_TODO',string>

const actions = createActionFactories<AddTodo | ToggleTodo>('ADD_TODO', 'TOGGLE_TODO')

store.dispatch(actions.ADD_TODO({ id: '1', objective: 'use conditional-types' }))
store.dispatch(actions.TOGGLE_TODO('1'))

Typescript and intellisense from code editors validate the action payloads against the type declarations, and with intellisense, writing the arguments for createActionFactories is a breeze.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment