Angular NgRx MemoizedSelector的类型定义学习

源代码位置:

Angular NgRx MemoizedSelector的类型定义学习

export interface MemoizedSelector<State, Result, ProjectorFn = DefaultProjectorFn<Result>> extends Selector<State, Result> {
    release(): void;
    projector: ProjectorFn;
    setResult: (result?: Result) => void;
    clearResult: () => void;
}

MemoizedSelector包含两部分属性:


extends Selector

Selector的定义:一个函数,输入参数类型为State,返回参数类型为Result,


因此,MemorizedSelector,首先它也是一个函数。

Angular NgRx MemoizedSelector的类型定义学习


在函数的基础上,MemoizedSelector多了下面四个属性:

Angular NgRx MemoizedSelector的类型定义学习


通过Object.assign, 将函数本身同 extends区块里定义的4个属性进行merge:


Angular NgRx MemoizedSelector的类型定义学习


export declare type DefaultProjectorFn<T> = (...args: any[]) => T;


同普通函数相比,DefaultProjectorFn的特点在于,限定了返回类型的类型为T, 在消费该类型时,必须指定该类型。


export type AnyFn = (...args: any[]) => any;

export type MemoizedProjection = {
    memoized: AnyFn;
    reset: () => void;
    setResult: (result?: any) => void;
    clearResult: () => void;
};
export type MemoizeFn = (t: AnyFn) => MemoizedProjection;
export type ComparatorFn = (a: any, b: any) => boolean;
export type DefaultProjectorFn<T> = (...args: any[]) => T;

export declare type Selector<T, V> = (state: T) => V;

export interface MemoizedSelector<State, Result, ProjectorFn = 

DefaultProjectorFn<Result>> extends Selector<State, Result> {
    release(): void;
    projector: ProjectorFn;
    setResult: (result?: Result) => void;
    clearResult: () => void;
}

export interface JerryState {
    name: string,
    age: number
}

let jerryProjector = (data: string) => data.length;

let jerryOriginFn = (data: JerryState) => data.name.length;

let jerrySelector: MemoizedSelector<JerryState, number, DefaultProjectorFn<number>>;

let oExtended = {
    release: () => {},
    projector: jerryProjector,
    setResult: (data: number) => {},
    clearResult: () => {}
};

jerrySelector = Object.assign(jerryOriginFn, oExtended);

console.log('Ethan', jerrySelector({ name: 'Jerry', age: 31}));
上一篇:user.config.ts文件里定义的配置是如何合并到SAP Spartacus的标准配置里去的


下一篇:一个字稳!云原生产品家族支撑冬奥会九大业务场景,打造云上奥运新体验