baetheus / dux

Tools for writing portable redux, flux, and ngrx code. Type safe and boilerplate reducing.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to correctly use ExtractAction for inferred type on RunEvery

smaccoun opened this issue · comments

Not sure if just need more documentation for ExtractAction, but I can't seem to get the right action type from my actionCreators for RunEvery.

const someAction = actionFactory<number>('SomeAction')
type SomeAction = ExtractAction<typeof someAction>


const setRetrieveState: RunEvery<any, SomeAction> = (state, action) => {
  const newValue = action.value + 1 // -- | ERROR! Object is of type unknown
  return from([{type: 'SettingSomeRetrieveState', value: newValue}])
}

Where typescript infers SomeAction as

type SomeAction = Action<unknown, Record<string, any>>

Ah, this is because actionFactory returns an ActionFunction, not an ActionCreator. The difference between the two is that ActionFunction only creates actions while ActionCreators have the match function. Here is one way to resolve the type problem:

import * as S from './src/Store';
import * as A from './src/Actions';
import { from } from 'rxjs';

const someActionGroup = A.actionCreatorFactory("GROUP");
const someAction = someActionGroup.simple<number>("SOME_ACTION")
type SomeAction = A.ExtractAction<typeof someAction>


const setRetrieveState: S.RunEvery<any, SomeAction> = (state, action) => {
  const newValue = action.value + 1;
  return from([{type: 'SettingSomeRetrieveState', value: newValue}])
}

You could also use the filterEvery combinator from Store.ts:

import * as S from './src/Store';
import * as A from './src/Actions';
import { from } from 'rxjs';

const someActionGroup = A.actionCreatorFactory("GROUP");
const someAction = someActionGroup.simple<number>("SOME_ACTION")

const setRetrieveState = S.filterEvery(someAction, (_, action) => {
  const newValue = action.value + 1;
  return from([{type: 'SettingSomeRetrieveState', value: newValue}])
});

Hope this helps!

That is perfect, thank you!

Closing as the answer was accepted.