Generic programming

Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.
把一个原本特定于某个类型的算法或类当中的类型信息抽掉,抽出来做成模板参数T
We need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned. Here, we will use a type variable, a special kind of variable that works on types rather than values.

Generic Types

The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations:
In a similar example, we may want to move the generic parameter to be a parameter of the whole interface. This lets us see what type(s) we're generic over. This makes the type parameter visible to call the other members of the interface.
Notice that out example has changed to be something slightly different. Instead of describing a generic function, we now have a non-generic function signature that is a part of the generic type.
⚠️
In addition to generic interfaces, we can also create generic classes. Note that it is not possible to create generic enums and namespace.

Generic Classes

 
As we covered in our section on classes, a class has two sides to its type: the static side and the instance side. Generic classes are only generic over their instance side rather than their static side, so when working with classes, static members can not use the class's type parameter.

Mapped types

A common task is to take an existing type and make each of its properties optional:
badge