NgRx createAction方法的返回类型签名的含义

我一直在通过NgRx Doumentation进行createaction方法,如下面的链接所示: Overloads for createAction method

我在下面无法理解此方法的类型签名,特别是createaction方法的返回类型:    什么是

() => Typedaction<T>

此签名中:

 actionCreator<T,() => Typedaction<T>>

我看不到对Typedaction的引用吗?这是否意味着具有特定操作类型形状的任何对象?

在返回类型的上述签名中,我对T的理解是,它是actionCreator函数的通用类型,该函数将在调用时返回T类型的action。 但是不确定其他Type参数是否指示,除了它似乎是某个返回T类型的Typedaction的函数外。 想知道一个真实的例子。

cc59625349 回答:NgRx createAction方法的返回类型签名的含义

TypedAction是一个通用接口,通过添加只读type属性扩展了Action类型。

export declare interface TypedAction<T extends string> extends Action {
  readonly type: T;
}

ActionCreator<T,() => TypedAction<T>>-告诉我们,我们有一个工厂返回TypedAction对象() => ({ type: T})

让我们定义一个动作创建者:

export const logout = createAction('[Auth] Logout');

createAction函数在action_creator.ts中定义。

export function createAction<T extends string>(
  type: T
): ActionCreator<T,() => TypedAction<T>>;

从声明中我们可以知道createAction将返回一个函数,该函数反过来返回一个对象,该对象的字符串属性为type

让我们深入探讨一下实际的实现。 当您不为动作创建者the following code is executed提供有效载荷时:

<T extends string>

defineType是:

export function createAction<T extends string,C extends Creator>(
  type: T,config?: { _as: 'props' } | C
): Creator {
...
    case 'empty':
      return defineType(type,() => ({ type }));
...
}

function defineType(type: string,creator: Creator): Creator { return Object.defineProperty(creator,'type',{ value: type,writable: false,}); } 接受类型(“ [Auth]注销”)和创建者-defineType。它返回创建者,但是具有新属性() => ({ type })。 因此,调用typelogout.type将返回相同的值-'[Auth]注销'

稍后,在reducer_creator.ts中,它允许我们extract ActionCreator type(在本例中为“ [Auth]注销”),将其与reducer函数关联,并与execute it

更新: 随着问题的答案越来越大,我决定写一篇博客文章How do NgRx Action Creators work

本文链接:https://www.f2er.com/3167993.html

大家都在问