简体   繁体   English

TypeScript:从“typeof”通用 function 获取通用 function 类型

[英]TypeScript: Get Generic function type from “typeof” generic function

I'm pretty sure TypeScript has a way of doing this but I haven't figured it out yet.我很确定 TypeScript 有办法做到这一点,但我还没有弄清楚。

Is there a way to extract a generic type from the typeof a generic function?有没有办法从泛型typeof的类型中提取泛型类型?

Consider this simple generic function:考虑这个简单的通用 function:

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

I want to extract the generic type of this function.我想提取这个function的泛型。 I tried:我试过了:

type IEchoFn = typeof echo;

But it's unusable:但它无法使用:

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

I thought I'd write it as我以为我会把它写成

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

But this is invalid syntax.但这是无效的语法。

How can I extract a generic type from the typeof a generic function (or its return value)?如何从泛型typeof (或其返回值)的类型中提取泛型类型?

Variables that has an explicit type are set in stone and can not be inferred from its value.具有显式类型的变量是一成不变的,无法从其值中推断出来。

This is one way to solve it:这是解决它的一种方法:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM