I was reviewing the code for the example application provided by NgRx. I noticed that each reducer function in the example application has a return value that is typed by the State
interface for that particular reducer. For example, the books reducer has the following code:
export interface State {
ids: string[];
entities: { [id: string]: Book };
selectedBookId: string | null;
}
export const initialState: State = {
ids: [],
entities: {},
selectedBookId: null,
};
export function reducer(
state = initialState,
action: book.Actions | collection.Actions
): State {
Later on, I was reading a book about NgRx titled Reactive Programming with Angular and NgRx by Oren Farhi, and came across a code snippet showing the common body structure of a reducer function (on pages 24-25.) The code for the common structure shows the return value of the reducer function as being typed by ActionReducer
with State
as the type parameter (called SomeInterface
rather than State
in this case):
export interface SomeInterface {
items: Item[],
filter: string
}
let initialState: SomeInterface = {
items: [],
filter: ''
}
export function MyReducer (
state: SomeInterface = initialState,
action: Action
): ActionReducer<SomeInterface> {
Why does one code sample use State and the other uses ActionReducer with State as the type parameter for the return value of reducer functions? Why would one choose one of these function signatures over the other? What purpose does each serve?
The book is written for NgRx 2.2.1 whereas the example application is for the latest version of NgRx (version 4.1.1.) I’m guessing that the difference in return types cannot simply be explained by the difference in NgRx versions, as the latest version of NgRx has ActionReducer as well.
Thank you!