Last active
April 22, 2020 17:46
-
-
Save deptno/f0ec5364d18823ff3f17854826a0673b to your computer and use it in GitHub Desktop.
strong typed redux action with [email protected]
This file contains 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
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