Last active
October 27, 2017 11:54
-
-
Save tstelzer/32ebc0172dde299ab318cab1b31aa60b to your computer and use it in GitHub Desktop.
How I type my reducers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Todo { | |
readonly id: string, | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The latest versions of TypeScript support enums. You can use those for the type keys.
Otherwise, the typing looks a little more complicated than what I have settled on with Idiomatic pattern.