-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathselectors.ts
More file actions
34 lines (30 loc) · 1.05 KB
/
selectors.ts
File metadata and controls
34 lines (30 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { isNil } from 'lodash';
import type { RootState } from 'reducers';
type SubSelectorOptions = {
nonNullable?: boolean;
};
export const makeSubSelector = <ReducerState>(rootSelector: (state: RootState) => ReducerState) => {
function subSelector<Key extends keyof ReducerState>(
key: Key,
options: SubSelectorOptions & { nonNullable: true }
): (state: RootState) => NonNullable<ReducerState[Key]>;
function subSelector<Key extends keyof ReducerState>(
key: Key,
options?: SubSelectorOptions & { nonNullable?: false }
): (state: RootState) => ReducerState[Key];
function subSelector<Key extends keyof ReducerState>(
key: Key,
options: SubSelectorOptions = {}
): (state: RootState) => ReducerState[Key] {
return (state: RootState) => {
const val = rootSelector(state)[key];
if (options.nonNullable && isNil(val)) {
throw new Error(
`Value ${key as string} of RootState is ${val}, while the selector should remain non-nullable.`
);
}
return val;
};
}
return subSelector;
};