
MemoizedSelector包含兩部分屬性:
- extends Selector<State,Result>
Selector的定義:一個函數,輸入參數類型為State,傳回參數類型為Result,
是以,MemorizedSelector,首先它也是一個函數。
- 在函數的基礎上,MemoizedSelector多了下面四個屬性:
通過Object.assign, 将函數本身同 extends區塊裡定義的4個屬性進行merge:
- 1
同普通函數相比,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}));