TypeScript泛型函数的类型 [英] TypeScript Type of generic function

查看:324
本文介绍了TypeScript泛型函数的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解TypeScript文档中的以下段落:

I can't get my head arround the following paragraph in the TypeScript documentation:

泛型函数的类型与非泛型函数的类型相似,首先列出类型参数,类似于函数声明:"

"The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations:"

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: <T>(arg: T) => T = identity;

最后一行是做什么的,为什么要使用它?

What does the last line do and why is it used?

据我了解,myIdentity是获取身份函数类型的变量?如果是这种情况,为什么我需要定义这样的变量?函数标识已经声明了我可以期望的返回类型.

As far as I understood, myIdentity is a variable which gets the type of the identity function? And if this is the case why do I need to define such a variable? The function identity already declares what return type I can expect.

推荐答案

最后一行声明一个名为myIdentity的变量.变量属于函数类型,是泛型函数(<T>使它成为泛型函数的签名,列表中可能包含更多类型实参),该变量接受类型为T的实参并返回类型的值T.然后使用identity函数初始化变量,该函数符合myIdentity声明的签名.

The last line declares a variable named myIdentity. The variable is of a function type, a generic function (the <T> makes the it the signature of a generic function, more type arguments could be in the list) which takes an argument of type T and returns a value of typeT. And then initializes the variable with the identity function which conforms to the declared signature of myIdentity.

您可能需要执行此操作,以便根据运行时条件为myIdentity分配不同的功能.或声明此类型的参数,并将其传递给以后可以调用它的函数.

You may want to do this in order to assign different functions to myIdentity based on runtime conditions. Or declare a parameter of this type and pass it to a function that can invoke it later.

这篇关于TypeScript泛型函数的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆