如何将状态更改操作提取到具有类型参数的命名函数? NgRx,Angular

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

有没有办法创建一个 命名的 状态更改函数,具有适当的参数类型,在创建 reducer 时将被 on 方法接受?

我想创建 onLoginSuccessful 函数来处理状态变化并可以传递给 reducer 中的 on 方法。

但是当我尝试创建 onLoginSuccessful 时,出现 TS 编译错误。

//== 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编译错误:

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)

尝试使用 ActionType<typeof loginSuccessful>:

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

// ...

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