如何在 NgRx createAction props<>() 中使用泛型类型
How to use Generic Type in NgRx createAction 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
使用 NgRx 11,您需要将 Props 更改为 ActionCreatorProps。
return createAction(name, props<T>() as ActionCreatorProps<T> & NotAllowedCheck<T>);
我想创建一个 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
使用 NgRx 11,您需要将 Props 更改为 ActionCreatorProps。
return createAction(name, props<T>() as ActionCreatorProps<T> & NotAllowedCheck<T>);