Skip to content

Instantly share code, notes, and snippets.

@roblafeve
Last active January 4, 2019 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roblafeve/6b0d3e81f25f97732b3bbdbf9329700c to your computer and use it in GitHub Desktop.
Save roblafeve/6b0d3e81f25f97732b3bbdbf9329700c to your computer and use it in GitHub Desktop.
Vanilla Redux w/ TypeScript
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