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字符串属性的对象,在我们的例子中为<T extends string>
让我们深入了解一下实际的实现。当您不为操作创建者提供有效负载时,将执行以下代码:
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.typeandlogout().type将返回相同的值 - '[Auth] Logout'
稍后,在 reducer_creator.ts 中,它允许我们提取 ActionCreator 类型(在我们的例子中为“[Auth] Logout”),将其关联到 reducer 函数并执行它
更新:随着问题的答案变得越来越大,我决定写一篇博客文章NgRx Action Creators 是如何工作的