首页 > 解决方案 > 打字稿:函数和类型的交集

问题描述

查看 ngrx 的 ActionCreator 的类型定义,它看起来像这样:

export declare type ActionCreator<T extends string = string, C extends Creator = Creator> = C & TypedAction<T>;

这里 TypedAction 定义为:

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

最后是创造者:

export declare type FunctionWithParametersType<P extends unknown[], R = void> = (...args: P) => R;
export declare type Creator<P extends any[] = any[], R extends object = object> = FunctionWithParametersType<P, R>;

在简化的形式中,ActionCreator 被定义为一个交集:

C & TypedAction<T>

如果 C 是一个函数(创建者)

(...args: P) => R;

和 TypedAction 被定义为

{ type: string; }

如何实例化?:

(...args: P) => R & { type: string; }

我很难理解函数和类型的交集的概念。有人可以解释一下吗?

更具体地说,我试图在不使用“createAction”函数(用于学习目的)的情况下创建 ActionCreator 的实例,但到目前为止还没有成功。此示例中的右侧应该是什么样子才能使其工作?:

const ac: ActionCreator<string, () => ({ b: number, type: string })> = ([]) => ({ b: 1, type: 'abc' });

错误是:

Type '([]: Iterable<any>) => { b: number; type: string; }' is not assignable to type 'ActionCreator<string, () => { b: number; type: string; }>'.
Type '([]: Iterable<any>) => { b: number; type: string; }' is not assignable to type '() => { b: number; type: string; }'.

标签: typescriptngrx

解决方案


函数也是对象,因此它们可以具有属性。您的实例看起来像这样

const result = ([]) => ({ b: 1});
result.type = "test";
const ac: ActionCreator<string, ([]) => {b: number}> = result;

游乐场


推荐阅读