打字稿:函数和类型的交集
Typescript: intersection of a function and a type
看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 是一个函数 (Creator)
(...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;
看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 是一个函数 (Creator)
(...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;