Skip to content

Instantly share code, notes, and snippets.

@tstelzer
Last active October 27, 2017 11:54
Show Gist options
  • Save tstelzer/32ebc0172dde299ab318cab1b31aa60b to your computer and use it in GitHub Desktop.
Save tstelzer/32ebc0172dde299ab318cab1b31aa60b to your computer and use it in GitHub Desktop.
How I type my reducers.
// Regular old action constant literal.
export const ADD = 'todos/ADD'
// Action type.
export type ADD = Action<'todos/ADD', {readonly todo: Todo}>
export type AllActions =
| ADD
export interface Todo {
readonly id: string,
}
export interface TodosEntities {
readonly [id: string]: Todo
}
type EntitiesReducer = Reducer<TodosEntities, ADD>
export const entitiesReducer: EntitiesReducer = (
s = {},
a,
) => {
switch (a.type) {
case ADD: return {...s, [a.payload.todo.id]: a.payload.todo}
default: return s
}
}
export interface Action<T, P> {
readonly type: T
readonly payload: P
readonly error?: boolean
readonly meta?: any
}
export type Reducer<S, A> = (
state: S,
action: A,
) => S
@TroySchmidt
Copy link

TroySchmidt commented Oct 27, 2017

The latest versions of TypeScript support enums. You can use those for the type keys.

export enum types {
  TOGGLE_USERS_TABLE = 'users/TOGGLE_USERS_TABLE',
  LOAD_USERS_REQUEST = 'users/LOAD_USERS_REQUEST',
  LOAD_USERS_RESPONSE = 'users/LOAD_USERS_RESPONSE',
  LOAD_USERS_FAIL = 'users/LOAD_USERS_FAIL',
  EDIT_USER_REQUEST = 'users/EDIT_USER_REQUEST',
  EDIT_USER_RESPONSE = 'users/EDIT_USER_RESPONSE',
  EDIT_USER_FAIL = 'users/EDIT_USER_FAIL',
  DELETE_USER_REQUEST = 'users/DELETE_USER_REQUEST',
  DELETE_USER_RESPONSE = 'users/DELETE_USER_RESPONSE',
  DELETE_USER_FAIL = 'users/DELETE_USER_FAIL',
  EDIT_UPDATE = 'users/EDIT_UPDATE',
  TOGGLE_EDIT_FORM = 'users/TOGGLE_EDIT_FORM',
  CREATE_NEW_USER = 'users/CREATE_NEW_USER',
  OTHER_ACTION = 'users/OTHER_ACTION',
}

Otherwise, the typing looks a little more complicated than what I have settled on with Idiomatic pattern.

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