< T>的目的是什么?内函数genericFunction< T>(arg:T):string {}` [英] What's the purpose of <T> inside `function genericFunction<T>(arg:T): string {}`
问题描述
我正在阅读关于TypeScript中的泛型函数此处。作者提供了一个通用函数的例子:
$ p $ function genericFunction< T>(arg:T):string {
返回arg.toString();
}
我很好奇的用途< T>
。没有它,这个
函数genericFunction(arg:T):string {
return arg.toString();
$ / code>
会给出错误错误:(1,30 )TS2304:找不到名字'T'。
。那么它不知何故告诉编译器,函数中指定的类型 T
应该被看作是泛型的?因此,为了定义一个简单的函数,我们需要使用name来定义一个泛型函数,我们需要使用 name< type here>
标识符?
最后,作者展示了< T>
的另一个用法:
function xValue< T extends Point>
它用于告诉编译器类型 T
将在 Point
接口上定义属性。
我明白通用函数是什么。这个问题是关于通用函数语法中< T>
标识符的用途的。
function genericFunction< T>
这里< T>
是将该泛型类型的 引入到此函数中。你基本上说我们在这里有一个函数,而且我们使用了一个泛型类型,它是T 。
介绍如果您省略< T> $ c $,那么您可以将它用作函数其余部分的类型。
I'm reading about generic functions in TypeScript here. The author provides an example of a generic function:
function genericFunction<T>(arg:T): string {
return arg.toString();
}
I'm curios of the purpose of <T>
. Without it, this
function genericFunction(arg:T): string {
return arg.toString();
}
will gives an error Error:(1, 30) TS2304:Cannot find name 'T'.
. So is it somehow telling compiler that the type T
specified in the function should be treated as generic? So to define a simple function we need to use name, to define a generic function, we need to use name<type here>
identifier?
At the bottom, the author shows another usage of <T>
:
function xValue<T extends Point>
which is used to tell a compiler that the type T
will have properties defined on the Point
interface.
I understand what a generic function is. The question is about the purpose of <T>
identifier in generic function syntax.
function genericFunction<T>
This <T>
here is the introduction of the generic type to this function. You're basically saying we have a function here, and we are using a generic type in it, and it is T.
Introducing the T there allows you to use it as a type in the rest of the function.
If you omit <T>
, the function does not know you're using a generic type and it will not work.
这篇关于< T>的目的是什么?内函数genericFunction< T>(arg:T):string {}`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!