Reputation: 31861
I'm trying to create a generic function that takes another function and infers the return type (similar to what map would do).
I have this code:
type game_selector<T> = <T>( state : GT.game_state ) => T
export function useGameState<T>( gs : game_selector<T> ): T {
And then I call it like this:
const users = useGameState( gs => gs.users )
I assume from the error, that type of gs
is properly inferred, since it correctly finds the type of gs.users
to be Users
. The error is:
TS2322: Type 'Users' is not assignable to type 'T'
How do I type this function correctly?
Upvotes: 1
Views: 82
Reputation: 5944
You have an unnecessary additional generic type here:
type game_selector<T> = <T>( state : GT.game_state ) => T;
The returned T
is actually this one: <T>(...)
, but I suspect you need the provided type from game_selector<T>
.
If you try this in the Typescript playground you will actually see a slightly greyed out T
in game_selector<T>
. When you hover over it, it shows you a warning saying:
'T' is declared but its value is never read.(6133)
This will fix it for you:
type game_selector<T> = ( state : GT.game_state ) => T;
Upvotes: 3