首页 > 解决方案 > 如何声明一个函数的类型,该函数在打字稿中返回具有推断类型的函数?

问题描述

我正在尝试为如下所示的函数创建类型:

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'.错误。

有没有正确的方法来做到这一点?

标签: typescript

解决方案


你不能创建一个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。


推荐阅读