typescript - 打字稿:函数和类型的交集
问题描述
查看 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; }'.
解决方案
函数也是对象,因此它们可以具有属性。您的实例看起来像这样
const result = ([]) => ({ b: 1});
result.type = "test";
const ac: ActionCreator<string, ([]) => {b: number}> = result;
推荐阅读
- java - 当组合框不是唯一标识时,如何将组合框值设置为数组值?
- c# - 不要纠正在 C# 中的输出
- android - 来自未发布版本的错误报告——我被黑了吗?
- javascript - 添加到数组的对象是按值传递的?
- laravel - 如何修复 Laravel 信息上的 Vue 安装错误
- java - 如何修复糟糕的基本解码?
- html - Text moving during the transition animation
- html - 我的文字
标签在我的 标签,无法弄清楚如何在我的页眉和页脚之间获取它 - python - Python import service_identity 错误:无法导入名称 DNSName
- java - ClassDiagramm 0..1 到 0..1 关系缺少转换成java代码的步骤