Skip to content

Instantly share code, notes, and snippets.

@deptno
Last active April 22, 2020 17:46
Show Gist options
  • Save deptno/f0ec5364d18823ff3f17854826a0673b to your computer and use it in GitHub Desktop.
Save deptno/f0ec5364d18823ff3f17854826a0673b to your computer and use it in GitHub Desktop.
strong typed redux action with [email protected]
function createAction<A extends ActionTypes>(type: A): TypedAction<A>
function createAction<A extends ActionTypes, P>(type: A, payload: P): TypePayloadAction<A, P>
function createAction(type, payload?) {
return payload !== undefined ? {type, payload} : {type}
}
enum ActionTypes {
ACTION_1 = 'action 1',
ACTION_2 = 'action 2'
}
const actions = {
actionA: () => createAction(ActionTypes.ACTION_1, {a:1}),
actionB: () => createAction(ActionTypes.ACTION_2, {b:1}),
}
interface TypedAction<A> {
type: A
}
interface TypePayloadAction<A, P> extends TypedAction<A> {
payload: P
}
function reducer(state: State, action: ReturnType<typeof actions[keyof typeof actions]>): State {
switch (action.type) {
case ActionTypes.ACTION_1:
action.payload.a
// action.payload.b // error
return {}
case ActionTypes.ACTION_2:
// action.payload.a // error
action.payload.b
return {}
}
}
interface State {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment