Here is the code snippet I'm working with:
export type Subscribe<T extends object> = <U>(
listener: (slice: U) => void,
selector: (state: T) => U,
) => void
// The actual implementation is not relevant
const subscribe = {} as Subscribe<{ value: number }>
subscribe(
(value) => value * 2, // TypeScript error: object is of type unknown
(state) => state.value
)
It seems that it's challenging to infer types in this manner using TypeScript.
However, when I switch the order of parameters, it works perfectly:
export type Subscribe<T extends object> = <U>(
selector: (state: T) => U,
listener: (slice: U) => void,
) => void
const subscribe = {} as Subscribe<{ value: number }>
subscribe(
(state) => state.value,
(value) => value * 2 // No errors now! Number type is inferred correctly
)
I'd like selector
to be the second parameter for optional purposes. Please inform me if this is unattainable or if you have a solution.