Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wuzzeb
wuzzeb / pledge-middleware.ts
Created September 29, 2019 19:41
Example typed redux middleware
export enum PledgeStatus {
Starting = "Pledge_Starting",
Completed = "Pledge_Completed",
Error = "Pledge_Error"
}
export type Pledge<T> =
| { status: PledgeStatus.Starting }
| { status: PledgeStatus.Completed; result: T }
| { status: PledgeStatus.Error; error: Error };
@wuzzeb
wuzzeb / App.tsx
Created September 29, 2019 18:07
Using the type-safe redux store in a component
import * as React from "react";
import { SampleActionType, useSelector, useDispatch } from "../store";
function IncrBtn(props: { value: number }) {
const incr = useDispatch(SampleActionType.IncrementNum);
//incr has type (payload: {by: number}) => void
return (
<p>
<button onClick={() => incr({ by: props.value })}>Incr by {props.value}</button>
</p>
@wuzzeb
wuzzeb / store-index.ts
Created September 29, 2019 18:07
Typescript redux store definition
import { createStore } from "./typed-redux";
import { compose, applyMiddleware } from "redux";
export { SampleState, SampleAction, SampleActionType } from "./sample";
import { sampleReducer } from "./sample";
/* tslint:disable */
const composeEnhancers =
typeof window === "object" && (window as any)["__REDUX_DEVTOOLS_EXTENSION_COMPOSE__"]
? (window as any)["__REDUX_DEVTOOLS_EXTENSION_COMPOSE__"]
@wuzzeb
wuzzeb / store-sample.ts
Created September 29, 2019 18:06
Sample typescript redux store
export interface SampleState {
num: number;
}
export enum SampleActionType {
IncrementNum = "Sample_Increment",
DecrementNum = "Sample_Decrement"
}
export type SampleAction =
@wuzzeb
wuzzeb / typed-redux.ts
Last active September 10, 2020 03:26
Type-safe react and redux actions
import * as React from "react";
import * as redux from "redux";
import * as reactRedux from "react-redux";
// a variant of middleware which tracks input and output types of the actions
export type Dispatch<A> = (a: A) => void;
export type Middleware<A1, A2> = (dispatch: Dispatch<A2>) => (a: A1) => void;
export function composeMiddleware<A1, A2, A3>(m1: Middleware<A1, A2>, m2: Middleware<A2, A3>): Middleware<A1, A3> {
return d => m1(m2(d));
}