Skip to content

Instantly share code, notes, and snippets.

@r-k-b
Created December 19, 2018 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-k-b/bfbb6675113b81c2201f93f72313e845 to your computer and use it in GitHub Desktop.
Save r-k-b/bfbb6675113b81c2201f93f72313e845 to your computer and use it in GitHub Desktop.
Getting type safety when using redux-loop's `Cmd.run`

The recommended usage of redux-loop's Cmd.run lacks type safety, which is problematic when a project relies on TypeScript.

Firstly, the args are typed any, and will not error when they don't match the arguments of the function to be run.

Second, the arguments to successActionCreator don't need to match the return type of the function to be run.

Replace usages of Cmd.run with typesafeCmdRun to get type safety.

If you need to pass arguments into the function, wrap it in a lambda expression.

Definition

function typesafeCmdRun<T>(
  f: () => Promise<T>,
  failActionCreator: (e: Error) => RootAction,
  successActionCreator: (args: T) => RootAction,
): RunCmd<RootAction> {
  return Cmd.run<RootAction>(f, {
    failActionCreator,
    successActionCreator,
  })
}

Examples

Before

// ...
case 'INIT':
  return loop<Model, RootAction>(
    state,
    Cmd.batch<RootAction>([
      Cmd.run<RootAction>(fetchStats, {
        args: [state.clientSettings],
        failActionCreator: dashboardDataFetchFailed,
        successActionCreator: dashboardDataFetchSuccessful,
      }),
      Cmd.run<RootAction>typesafeCmdRun(fetchDomainGroups, {
        args: [],
        failActionCreator: domainGroupFetchFailed,
        successActionCreator: domainGroupFetchSuccessful,
      ),
    ]),
  )
// ...

After

// ...
case 'INIT':
  return loop<Model, RootAction>(
    state,
    Cmd.batch<RootAction>([
      typesafeCmdRun(
        () => fetchStats(state.clientSettings),
        dashboardDataFetchFailed,
        dashboardDataFetchSuccessful,
      ),
      typesafeCmdRun(
        fetchDomainGroups,
        domainGroupFetchFailed,
        domainGroupFetchSuccessful,
      ),
    ]),
  )
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment