为什么泛型的类型变量通常声明为单个字母(例如:<T>)?
Why are type variables for generics commonly declared as a single letter (e.g.: <T>)?
对于 TypeScript generics documentation 和我遇到的大多数类型定义文件中的每个示例,类型变量都声明为单个字母,通常是 <T>
.
示例:
function identity<T>(arg: T): T {
return arg;
}
问题:
- 为什么泛型的类型变量通常声明为单个字母?
- 这样做的原因是什么?
- 除了约定俗成和简洁之外,它还有其他用途吗?
- 使用更具描述性的名称的优缺点是什么?
Generics Types 的 Java 文档对此有一段非常好的介绍 - 它适用于所有支持类型变量的语言:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
....
T - Type
基本上,您希望能够快速识别出某些东西是类型变量,并且命名类型变量 T
只是在某些时候成为标准代码约定。
对于 TypeScript generics documentation 和我遇到的大多数类型定义文件中的每个示例,类型变量都声明为单个字母,通常是 <T>
.
示例:
function identity<T>(arg: T): T {
return arg;
}
问题:
- 为什么泛型的类型变量通常声明为单个字母?
- 这样做的原因是什么?
- 除了约定俗成和简洁之外,它还有其他用途吗?
- 使用更具描述性的名称的优缺点是什么?
Generics Types 的 Java 文档对此有一段非常好的介绍 - 它适用于所有支持类型变量的语言:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
....
T - Type
基本上,您希望能够快速识别出某些东西是类型变量,并且命名类型变量 T
只是在某些时候成为标准代码约定。