我想创建一个 NgRx 动作创建器工厂。但我不知道如何将泛型类型传递给props
method.
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");
你可以自己尝试一下斯塔克闪电战 https://stackblitz.com/edit/ngrx-generic-props?file=index.ts
它似乎@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
堆栈闪电战 https://stackblitz.com/edit/ngrx-generic-props-fcvrao?file=index.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)