gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:07:02 28 4
gpt4 key购买 nike

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

我无法理解下面这个方法的类型签名,特别是 createAction 方法的返回类型:
什么是

() => TypedAction<T>

在这个签名中:
 ActionCreator<T, () => TypedAction<T>>

我没有看到对 TypedAction 的任何引用?这是否意味着任何特定 Action 类型的形状对象?

我在上面的返回类型签名中对 T 的理解是,它是 ActionCreator 函数的泛型类型,它在调用时将返回类型为 T 的 Action。
但不确定其他类型参数是否表明它似乎是返回 TypedAction 的某个函数T 型。
想知道一个真实世界的例子。

最佳答案

TypedAction是一个通用接口(interface),它通过添加只读 type 来扩展 Action 类型属性(property)。

export declare interface TypedAction<T extends string> extends Action {
readonly type: T;
}
ActionCreator<T, () => TypedAction<T>> - 告诉我们我们有一个工厂,它返回一个 TypedAction 对象 () => ({ type: T})
让我们定义一个 Action 创建者:
export const logout = createAction('[Auth] Logout');
createAction函数在 action_creator.ts 中定义。
export function createAction<T extends string>(
type: T
): ActionCreator<T, () => TypedAction<T>>;

从声明中我们可以看出 createAction将返回一个函数,该函数又返回一个带有 type 的对象在我们的例子中,字符串的属性为 <T extends string>
让我们深入了解一下实际的实现。
当您不为 Action 创建者提供有效负载时 the following code is executed :
export function createAction<T extends string, C extends Creator>(
type: T,
config?: { _as: 'props' } | C
): Creator {
...
case 'empty':
return defineType(type, () => ({ type }));
...
}

而defineType是:
function defineType(type: string, creator: Creator): Creator {
return Object.defineProperty(creator, 'type', {
value: type,
writable: false,
});
}
defineType接受类型 ('[Auth] Logout') 和 Creator - () => ({ type }) .它返回 Creator 但带有一个新属性 type .
所以调用 logout.typelogout().type将返回相同的值 - '[Auth] Logout'

稍后,在 reducer_creator.ts 中,它允许我们 extract ActionCreator type (在我们的例子中是“[Auth] Logout”),将它与 reducer 函数和 execute it 相关联

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

关于typescript - NgRx createAction 方法返回类型签名的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690209/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com