如何在 NgRx createAction props<>() 中使用通用类型

flo*_*olu 7 typescript ngrx

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

import { createAction, props } from "@ngrx/store";

function actionFactory<T>(name: string) {
  return createAction(name, props<T>());
//                          ^^^^^^^^^^
}
Run Code Online (Sandbox Code Playgroud)

它抛出这个错误

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

我需要如何修改工厂方法才能将泛型类型传递给props这样的方法?:

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

你可以在Stackblitz上亲自尝试一下

art*_*iak 8

@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
Run Code Online (Sandbox Code Playgroud)

堆栈闪电战