Skip to content

Instantly share code, notes, and snippets.

@alecmerdler
Created November 30, 2018 20:32
Show Gist options
  • Save alecmerdler/da71ec2f7a6d764c8ecb302a77226368 to your computer and use it in GitHub Desktop.
Save alecmerdler/da71ec2f7a6d764c8ecb302a77226368 to your computer and use it in GitHub Desktop.
TypeScript-ify Redux Store

Description

Defines the app's Redux store using TypeScript to add type safety and improve developer documentation.

The general strategy to get TypeScript to work nicely with ImmutableJS is to:

  1. Define ReducerNameStateData type (the raw, JSON-serializable state)
export type MyReducerStateData = {
  currentUser: string;
  data: {
    loaded: boolean;
  };
};
  1. Define ReducerNameState type, which extends Immutable.Map and overrides some methods
export interface MyReducerState extends ImmutableMap<string, any> {
  toJS(): MyReducerStateData;
  get<K extends keyof MyReducerStateData>(key: K, notSetValue?: MyReducerStateData[K]): MyReducerStateData[K];
  set<K extends keyof MyReducerStateData>(key: K, val: MyReducerStateData[K]): MyReducerStateData;
}
  1. Use the ReducerNameState in the actual reducer function and createStore() call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment