Is there a method to eliminate the as any
in the update_substate
function? It seems type-safe when directly invoking the update_state function, so it should also be safe when invoked indirectly, right? These functions are meant to be lightweight helpers for managing Redux state. I have come across some related questions ([1], [2], [3]), but I haven't fully grasped the solutions yet.
export function update_state <
RootState,
P1 extends keyof RootState,
S1 extends RootState[P1],
> (root_state: RootState, path1: P1, replacement_state: S1)
{
const current = root_state[path1]
if (current === replacement_state) return root_state
return {
...root_state,
[path1]: replacement_state
}
}
export function update_substate <
RootState,
P1 extends keyof RootState,
S1 extends RootState[P1],
P2 extends keyof S1,
S2 extends S1[P2],
> (root_state: RootState, path1: P1, path2: P2, replacement_substate: S2)
{
/**
Without the `as any` will get the error:
Argument of type 'RootState[P1]' is not assignable to parameter of type 'S1'.
'S1' could be instantiated with an arbitrary type which could be unrelated to 'RootState[P1]'.
Type 'RootState[keyof RootState]' is not assignable to type 'S1'.
'S1' could be instantiated with an arbitrary type which could be unrelated to 'RootState[keyof RootState]'.
Type 'RootState[string] | RootState[number] | RootState[symbol]' is not assignable to type 'S1'.
'S1' could be instantiated with an arbitrary type which could be unrelated to 'RootState[string] | RootState[number] | RootState[symbol]'.
Type 'RootState[string]' is not assignable to type 'S1'.
'S1' could be instantiated with an arbitrary type which could be unrelated to 'RootState[string]'.ts(2345)
*/
const replacement_state = update_state<S1, P2, S2>(root_state[path1] as any, path2, replacement_substate)
return update_state(root_state, path1, replacement_state)
}