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:
< 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.
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.
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)
Yes, it is mandatory to specify it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With