【问题标题】:TypeScript: Get Generic function type from "typeof" generic functionTypeScript:从“typeof”泛型函数获取泛型函数类型
【发布时间】:2020-11-15 18:00:24
【问题描述】:

我很确定 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 一个泛型函数(或其返回值)中提取泛型类型?

【问题讨论】:

  • 您可以将通用函数分配给具体函数,但不能反过来。这会起作用:const echo2: (input: string) =&gt; string = echo;
  • 我也遇到了同样的问题。通常,我们使用具有复杂模板类型的函数的包。通常使用typeof fn 是有利的,但是如果没有分配模板类型的方法,我们就不能使用typeof。它会导致一些非常难看的打字。

标签: typescript generics


【解决方案1】:

具有显式类型的变量是一成不变的,无法从其值中推断出来。

这是解决它的一种方法:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2019-05-06
    • 1970-01-01
    相关资源
    最近更新 更多