Reputation: 113
I'm trying to create type for functions that look like this:
const someSelector1 = (state: ContextState) => () => state.currentName;
const someSelector2 = (state: ContextState) => (id: string) => state[id].values;
I would like to create type that would be assigned to the "someSelector" functions, and that would infer types of the return function. Something like this:
type Selector = <F extends Function>(state: ContextState) => F
const someSelector1: Selector = (state) => () => state.currentName;
const someSelector2: Selector = (state) => (id: string) => state[id].values;
Unfortunately, with this implementation I'm getting Type '(id: string) => string' is not assignable to type 'F'. '(id: string) => string' is assignable to the constraint of type 'F', but 'F' could be instantiated with a different subtype of constraint 'Function'.
error.
Is there a correct way to do this?
Upvotes: 1
Views: 65
Reputation: 2572
You can't make a Selector
type with no generics, but consider where you take in your Selector
-typed arguments. In the function that uses the selectors, you can annotate the return type to give the return type of your selector like this:
type Selector<T extends () => any> = (state: ContextState) => T;
function applySelector<T extends () => any>(selector: Selector<T>): ReturnType<T> {
// code
}
Now calling applySelector
with a selector that returns T will also return T.
Upvotes: 1