I'm facing an issue with TypeScript where I need to solve a problem:
type State = {
alpha: string,
beta: number
}
const selectors = {
alpha: (s: State) => s.alpha,
beta: (s: State) => s.beta
}
function createModifiedSelector<T, S, U>(
modifyState: (differentState: T) => S,
selector: (state: S) => U,
) {
return (differentState: T) => selector(modifyState(differentState));
}
const add2State = (state: any) => {
return {...state, alpha: "abc", beta: 123}
}
// everything is fine so far
const modifiedAlpha = createModifiedSelector(add2State, selectors.alpha)
console.log(modifiedAlpha({}));
// However, how can I convert the entire selectors object if there are multiple selectors?
function createModifiedSelectorsObj<T, S, R extends typeof selectors>(modifyState: (differentState: T) => S, selectors: R) {
const result: Record<keyof R, any> = selectors;
let selectorKey: keyof R;
for (selectorKey in selectors) {
result[selectorKey] = createModifiedSelector(modifyState, selectors[selectorKey])
}
return result;
}
In TypeScript, is there a way to provide correct typings for createModifiedSelectorsObj
and the return values of the selector functions?