Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are type variables for generics commonly declared as a single letter (e.g.: <T>)?

For every example in the TypeScript generics documentation and in most type definition files I've came across, type variables are declared as a single letter, usually <T>.

Example:

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

Questions:

  • why are type variables for generics commonly declared as a single letter?
    • what are the reasons for doing this?
    • does it have a purpose other than convention and brevity?
  • what are the pros and cons of using of more descriptive names?
like image 572
Willem-Aart Avatar asked Mar 30 '19 18:03

Willem-Aart


People also ask

What does T stand for in generics?

< T > is a conventional letter that stands for "Type", and it refers to the concept of Generics in Java. You can use any letter, but you'll see that 'T' is widely preferred. WHAT DOES GENERIC MEAN? Generic is a way to parameterize a class, method, or interface.

What letters do you use for generics?

Also, K is often used for a generic key type and V for a value type associated with it; in some cases E is used for the type of "elements" in a collection. Just to add - it's rare but occasionally you can use something more than letters for generic types.

What is E and T in Java generics?

T is meant to be a Type. E is meant to be an Element ( List<E> : a list of Elements) K is Key (in a Map<K,V> ) V is Value (as a return value or mapped value)

Is it necessary to use T as the name of a type parameter?

Yes, it is mandatory to specify it.


1 Answers

The Java docs for Generics Types has a really good paragraph about this - and it applies to all languages that supports type variables:

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

Basically you want to be able to quickly recognize that something is a type variable, and naming the type variable T just became a standard code convention at some point.

Microsoft's docs on C++ and C# has this convention too.

like image 112
Daniel Avatar answered Sep 29 '22 16:09

Daniel