TypeScript:从“ typeof”通用函数中获取通用函数类型

时间:2020-07-26 08:24:38

标签: typescript generics

我很确定TypeScript可以做到这一点,但我还没有弄清楚。

是否可以从typeof泛型函数中提取泛型?

考虑这个简单的通用函数:

function echo<T> (input: T) {
   return input;
}

我想提取此函数的通用类型。我尝试过:

type IEchoFn = typeof echo;

但这是不可用的:

const echo2: IEchoFn = (input: string) => input;
      ^^^^^
      // Type '(input: string) => string' is not 
      // assignable to type '<T>(input: T) => T'.

我以为我会写成

type IEchoFn<T> = (typeof echo)<T>;

但这是无效的语法。

如何从typeof泛型函数(或其返回值)中提取泛型类型?

1 个答案:

答案 0 :(得分:0)

具有显式类型的变量设置在石头上,无法根据其值进行推断。

这是解决问题的一种方法:

type IEchoFn<T> = (input: T) => T

const echo2: IEchoFn<string> = arg => arg