[2019-12-13] Generic

Component not only supports current data type, but also to support future data type, which provides a very flexible feature for you when creating large systems

1, generics

 

 We give identity3 add a variable of type T. T helped us capture the user's incoming type (for example: Number), then we can use this type. Then we again used the T as the return type. Now we can know the parameter types and return type is the same.

This allows us to track the use of the function in the type of information

We identity3 function called generics, because it can be applied to multiple types. Instead of using any, it will not lose information, so as to maintain the accuracy of the first example, the incoming numeric type and return value type

We define a generic function can be used in two ways

 

 For incoming type output2 we did not use angle brackets <> to clear; the compiler can see the value 4, then T is set to its type. Type inference helps us to keep the code lean and highly readable. If the compiler can not automatically infer the type, you can only clear as above, incoming type T.

2, the use of generic variables

 

 We can also use the generic type variable T as part of, rather than as whole type, as follows:

 

 3, generic type

On one, we create a common identity function can be applied to different types. In this section, we looked at what type of the function itself, as well as how to create a generic interface

 

 We can also use different generic parameter name, as long as can correspond in quantity and you can use

 

 We can also use with a call to the signature object literal to define a generic function

 

This leads us first to write a generic interface, the object literal example above out as an interface

 

We can put the generic parameter as a parameter for the entire interface. So we can clearly know which specific use of generic type

 

Note: You can not create a generic enumeration and generic namespace

4, generic class

Generic class and generic interface looks the same. Using generic class <> enclosed generic type, followed after the class name

 

Like interfaces directly to the generic type on the back of the class, we can help make sure that all properties of the class are using the same type.

我们在类章节说过,类有两部分:静态部分和实例部分。泛型类型指的是实例部分的类型,所以类的静态属性不能使用这个泛型类型

5、泛型约束

我们直接操作泛型类型的参数,但是编译器不能证明每种类型都有length属性,所以就会报错

相比于操作any所有类型,我们想要限制函数去处理带有.length属性的所有类型。只要传入的类型有这个属性。我们就允许,就是说至少包含这一个属性。为此,我们需要列出对于T的约束要求

为此,我们定义一个接口来描述约束条件。创建一个包含.lenght属性的接口,使用这个接口和extends关键字来实现约束

 

 在泛型约束中使用类型参数

 

 如果键值不属于对象,则会报错

在泛型里使用类类型

 

使用原型属性推断并约束构造函数与类实例的关系

Guess you like

Origin www.cnblogs.com/QQ-lala/p/12036753.html