首页 > 解决方案 > TypeScript argument type inference for a generic function argument with return?

问题描述

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?

标签: typescripttypescript-generics

解决方案


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;

推荐阅读