How extract state change action to a named function with typed parameters? NgRx, Angular

Is there a way to create a named state change function, with proper parameter types, that will be accepted in the on method when creating a reducer?

I would like to create onLoginSuccessful function that will handle state change and can be passed to the on method in the reducer.

But when I tried to create onLoginSuccessful, I am getting TS compilation error.

//== actions.ts file ==//
export const loginSuccessful = createAction(
    '[Login page] Login successful',
    props<{authToken: string}>()
);

//== reducer.ts file ==//
export const initialState: AuthState = {
    authToken: null
};

// this works
export const reducer = createReducer(
    initialState,
    on(loginSuccessful, (state, action) => {
        return {
            ...state,
            authToken: action.authToken
        };
    })
);

// this does NOT work
// creating named function onLoginSuccess with typed params
function onLoginSuccess(state: AuthState, action: typeof loginSuccessful): AuthState {
    return {
        ...state,
        authToken: action.authToken
    };
}

export const reducer = createReducer(
    initialState,
    on(loginSuccessful, onLoginSuccess) // <-- here on "onLoginSuccess" param throws TS compiler an error
);

TS compilation error:

Argument of type ‘(state: AuthState, action: ActionCreator<“[Login page] Login successful”, (props: { authToken: string; }) => { authToken: string; } & TypedAction<“[Login page] Login successful”>>) => AuthState’ is not assignable to parameter of type ‘OnReducer<AuthState, [ActionCreator<“[Login page] Login successful”, (props: { authToken: string; }) => { authToken: string; } & TypedAction<“[Login page] Login successful”>>]>’. Types of parameters ‘action’ and ‘action’ are incompatible. Type ‘{ authToken: string; } & TypedAction<“[Login page] Login successful”> & { type: “[Login page] Login successful”; }’ is not assignable to type ‘ActionCreator<“[Login page] Login successful”, (props: { authToken: string; }) => { authToken: string; } & TypedAction<“[Login page] Login successful”>>’. Type ‘{ authToken: string; } & TypedAction<“[Login page] Login successful”> & { type: “[Login page] Login successful”; }’ is not assignable to type ‘(props: { authToken: string; }) => { authToken: string; } & TypedAction<“[Login page] Login successful”>’. Type ‘{ authToken: string; } & TypedAction<“[Login page] Login successful”> & { type: “[Login page] Login successful”; }’ provides no match for the signature ‘(props: { authToken: string; }): { authToken: string; } & TypedAction<“[Login page] Login successful”>’.ts(2345)

Answer

Try using ActionType<typeof loginSuccessful>:

import { ActionType } from "@ngrx/store";

// ...

function onLoginSuccess(state: AuthState, action: ActionType<typeof loginSuccessful>): AuthState {
  return {
    ...state,
    authToken: action.authToken
  };
}