关于TS 泛型类型的问题

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

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

初学ts, <T>(arg: T) => T = identity 怎么理解这句的意思啊,类型是回调吗?
阅读 8.3k
4 个回答

类型是lambda表达式,也就是箭头函数,是一种函数,你也看到了,identity赋值给myIdentity,identity是一个函数,所以myIdentity类型肯定是函数。

<T>(arg: T) => T这个箭头函数类型表示,函数有一个参数,类型为T,函数返回值是T,可以参考es5/es6的lambda表达式。

加一个括号就好理解了

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

可以看作

let myIdentity: string = identity;

<T>(arg: T) => T 作为整体,相当于 string,是对其左侧变量的约束。

<T>(arg: T) => T function identity<T>(arg: T): T 中的后半部分其实是一个意思,约束了函数identity 的参数类型和返回值的类型

(arg: string) => string

表示这是一个方法,参数string类型,返回值string类型

<T>(arg: T) => T

表示这是一个泛型方法,给定类型T,则参数是T类型,返回值也是T类型

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进