typescript - 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?
解决方案
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;
推荐阅读
- robotframework - 如何通过选择文件从 Mac 上传本地文件
- html - 如何在我的 HTML 页面上使用 reactjs 显示此 json 数据
- c# - 我是否必须连接到本地数据库才能使用它的表值?如何访问表值?
- android - java.lang.RuntimeException: 传递结果失败 ResultInfo{who=null, request=4, result=-1, data=Intent
- android - 每当我尝试运行我的 Flutter 应用程序时执行此任务的“app:transformClassesWithMultidexlistForDebug”
- python - 断句并动态重排重框
- spring-cloud-gateway - Spring Cloud Gateway 线程同步还是异步的问题?
- architecture - Azure函数ServiceBusTrigger消息处理器设计
- python - 使用带有一组规则的递归查找最长路径
- node.js - 是否可以使用 AWS-SDK 直接从 S3 将文件流式传输到客户端?