如何在 NgRx 中创建操作 props 中使用泛型类型<>()



我想创建一个NgRx动作创建器工厂。但是我不知道如何将泛型类型传递给props方法。

import { createAction, props } from "@ngrx/store";
function actionFactory<T>(name: string) {
return createAction(name, props<T>());
//                          ^^^^^^^^^^
}

抛出这个错误

Type 'Props<T>' provides no match for the signature '(...args: any[]): object'

我需要如何修改工厂方法来传递一个泛型类型到props方法像这样?:

const action = actionFactory<{ id: string }>("sample");

你可以在Stackblitz上自己试试

似乎@ngrx/store-出于某些原因-阻止创建空对象的操作。以下是考虑@ngrx/store需求并使操作完全类型化的可能解决方案:

import { createAction, props, Props, NotAllowedCheck } from "@ngrx/store";
// T extends object meets the condition of props function
function actionFactory<T extends object>(name: string) {
// restricting config type to match createAction requirements
return createAction(name, props<T>() as Props<T> & NotAllowedCheck<T>);
}
// ok
const action = actionFactory<{ id: string }>("sample");
// empty object picked up on type level
const emptyAction = actionFactory<{}>("sample");
emptyAction({}); // error as expected properly

STACKBLITZ

在NgRx 11中,你需要将Props更改为ActionCreatorProps。

return createAction(name, props<T>() as ActionCreatorProps<T> & NotAllowedCheck<T>);

最新更新