Uncertain if the question is formulated correctly, but I am attempting to deduce the result type without knowing exactly how to achieve it.
This is my current approach:
type StateSetter<S> = (prevState: S) => S;
type ResolvableHookState<S> = S | StateSetter<S>;
export function resolveHookState<S>(state: S): S;
export function resolveHookState<S>(state: StateSetter<S>, currentState?: S): S;
export function resolveHookState<S>(state: ResolvableHookState<S>, currentState?: S): S {
if (typeof state === 'function') {
return (state as StateSetter<S>)(currentState as S);
}
return state;
}
This is how I intend to utilize it:
function someFunction(initialState: ResolvableHookState<number> = 0){
const resolvedState = resolveHookState(initialState);
}
The objective is for resolveHookState(initialState)
to return the number type, but currently it returns
ResolvableHookState<number>
due to certain constraints.
I attempted to achieve this through type inference, but the results were not as expected.
type ResolvableHookStateType<S extends ResolvableHookState<any>> = S extends StateSetter<infer T> ? T : S;
[UPD 1]
After some exploration, I arrived at the following solution:
export type StateSetter<S> = (prevState?: S) => S;
export type ResolvableHookState<S> = S | StateSetter<S>;
type ResolvableHookStateType<S> = S extends ResolvableHookState<infer T> ? T : never;
export function resolveHookState<S>(state: S): ResolvableHookStateType<S>;
export function resolveHookState<S>(state: StateSetter<S>, currentState?: S): ResolvableHookStateType<S>;
export function resolveHookState<S>(state: ResolvableHookState<S>, currentState?: S): ResolvableHookStateType<S> {
if (typeof state === 'function') {
return (state as StateSetter<S>)(currentState) as ResolvableHookStateType<S>;
}
return state as ResolvableHookStateType<S>;
Although effective, I am unsure if this is the most elegant way to address the issue.