typescript - 如何声明一个函数的类型,该函数在打字稿中返回具有推断类型的函数?
问题描述
我正在尝试为如下所示的函数创建类型:
const someSelector1 = (state: ContextState) => () => state.currentName;
const someSelector2 = (state: ContextState) => (id: string) => state[id].values;
我想创建将分配给“someSelector”函数的类型,并推断返回函数的类型。像这样的东西:
type Selector = <F extends Function>(state: ContextState) => F
const someSelector1: Selector = (state) => () => state.currentName;
const someSelector2: Selector = (state) => (id: string) => state[id].values;
不幸的是,通过这个实现我得到了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'.
错误。
有没有正确的方法来做到这一点?
解决方案
你不能创建一个Selector
没有泛型的类型,但要考虑你在哪里接受你的Selector
-typed 参数。在使用选择器的函数中,您可以注释返回类型以给出选择器的返回类型,如下所示:
type Selector<T extends () => any> = (state: ContextState) => T;
function applySelector<T extends () => any>(selector: Selector<T>): ReturnType<T> {
// code
}
现在使用返回 T 的选择器调用applySelector
也将返回 T。
推荐阅读
- python - 如何识别彼此特定距离内的坐标
- oracle-apex - 是否可以将表中的列作为 Oracle APEX 中的值创建一个方面?
- php - 在 WooCommerce 购物车页面上显示选定的产品变体
- python - 尝试使用 run_forever 创建一个永远运行的异步函数
- typescript - 有没有办法用打字稿中的一种类型检查来检查两种泛型类型
- python - 我找不到它的类名,我不能,因为它一直在改变它的位置
- angular - Angular - 图像未存储到数据库和文件目录中
- python - 从 kivy ,kv 文件中的按钮制作标签
- psql - 看不到查询输出
- cmake - 使用静态库时出现分段错误