Reputation: 2961
Since the type of of a reducer is defined as
export type Reducer<T> = (state: T | undefined) => T | undefined;
In my reducers that are not the initial reducer, I must declare
state = state as State
Am I missing something, or is this considered a minor inconvenience, please?
Upvotes: 1
Views: 38
Reputation: 13994
Non-initial reducers can be typed (in TypeScript) as (state: T) => T
and these will be compatible with the Reducer<T>
type found in the library. Here is an example from my codebase, the first snippet is an initial reducer that needs to treat the case for undefined:
const initReducer$ = xs.of(function initReducer(prev?: State): State {
if (prev) {
return prev;
} else {
return {
selfFeedId: '',
currentTab: 0,
};
}
});
This second snippet is a non-initial reducer where I am sure the previous state is not undefined:
const setSelfFeedId$ = ssbSource.selfFeedId$.map(
selfFeedId =>
function setSelfFeedId(prev: State): State {
return {...prev, selfFeedId};
},
);
Notice that when these streams are merged, the resulting type can be Stream<Reducer<State>>
with no casting involved:
const reducer$: Stream<Reducer<State>> = xs.merge(initReducer$, setSelfFeedId$);
Upvotes: 0