Last active
January 4, 2019 20:31
-
-
Save roblafeve/6b0d3e81f25f97732b3bbdbf9329700c to your computer and use it in GitHub Desktop.
Vanilla Redux w/ TypeScript
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
const enum ActionTypes { | |
A1 = "A1", | |
A2 = "A2", | |
} | |
type ReduxAction<Type extends ActionTypes, Payload> = { | |
type: Type, | |
payload: Payload | |
} | |
type ReduxActionCreator< | |
Type extends ActionTypes, | |
Payload, Args extends Array<any> = [] | |
> = (...args: Args) => ReduxAction<Type, Payload> | |
type A = ReduxActionCreator<ActionTypes.A1, { foo: string }, [string]> | |
const action1: A = (x) => { | |
return { | |
type: ActionTypes.A1, | |
payload: { foo: x } | |
} | |
} | |
type B = ReduxActionCreator<ActionTypes.A2, { bar: number, baz: string }, [number, string]> | |
const action2: B = (x, y) => { | |
return { | |
type: ActionTypes.A2, | |
payload: { bar: x, baz: y } | |
} | |
} | |
type Action = ReturnType<typeof action1> | ReturnType<typeof action2>; | |
interface State { | |
stuff: string | null; | |
otherStuff: { | |
bar: number; | |
baz: string | |
} | |
} | |
const initialState = { | |
stuff: null, | |
otherStuff: { | |
bar: 0, | |
baz: "ZERO" | |
} | |
} | |
const reducer = (state: State = initialState, action: Action) => { | |
switch(action.type) { | |
case ActionTypes.A1:{ | |
return {...state, stuff: action.payload.foo } | |
} | |
case ActionTypes.A2:{ | |
return {...state, otherStuff: action.payload } | |
} | |
default: | |
return state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment