<>typeScript Generics in

* Definition of generics
* Generic Functions
* Generic class
* generic interface
<>1, Definition of generics

generic paradigm : In software engineering , We don't just have to create consistent well-defined API, Also consider reusability .
Components can not only support the current data type , It also supports future data types , This gives you very flexible functionality when creating large systems .

In the image C# and Java In such a language , You can use generics to create reusable components , A component can support multiple types of data . This allows users to use the component with their own data type .

folk understanding : Generics are solutions class Interface Method reusability , And support for unspecified data types ( Type verification )

<>2, Generic Functions

Can only return string Type of data

function getData(value:string):string{
return value;

Need to return at the same time string type and number type ( Code redundancy )
function getData1(value:string):string{
return value;
function getData2(value:number):number{
return value;

Return at the same time string type and number type ,any It can solve this problem
function getData(value:any):any{
return value+‘hello’;

any Type checking abandoned , The parameter types passed in and returned can be inconsistent
//any There are problems , The type of value passed in , But the return value cannot be obtained Type of function getData<T>(value:T):any{ return
'2145214214'; } getData<number>(123); // Parameter must be number getData<string>(' This is a generic ');
If you need to pass in what Back to what . such as : afferent number Type must return number type afferent string Type must return string type

generic paradigm :
Is defined in the function / Interface / Class time , No specific type is specified in advance , A feature of the type is specified when it is used ;
It can support unspecified data types requirement : The parameters passed in are the same as those returned

T Represent generics , The specific type is determined when the method is called
//T Generic variable Represents any type function getData<T>(value:T):T{ return value; } getData<number>
(123); getData<string>('1214231'); getData<number>('2112'); /* Wrong way of writing */ //
Is defined in the function / Interface / Class time , No specific type is specified in advance , A feature of the type is specified when it is used ; //T Generic variable Represents any type function fun3<T>(
name:T):T{ console.log('hello ' + name); return name; }; fun3<string>('abc');
// After defining a generic function , How to pass in parameters // Define multiple types fun3<string | number>('abc');
<>3. Generic class

demand : For example, there is a minimum heap algorithm , Need to support both return numbers and strings a - z Two types . It is implemented by generics of classes
// The following one can only support numeric types class MinClass{ public list:number[]=[]; add(num:number){ this.
list.push(num) } min():number{ // var minNum = Math.min(...this.list) // Because you have to compare numbers
and character string , So use the following method var minNum=this.list[0]; for(var i=0;i<this.list.length;i++){ if(
minNum>this.list[i]){ minNum=this.list[i]; } } return minNum; } } var m=new
MinClass(); m.add(30); m.add(22); m.add(6); alert(m.min());
How to just numbers and numbers at the same time How about the parameter comparison size of the string ?

Using generics of classes
class MinClas<T> { public list: T[] = []; add(value: T): void { this.list.push(
value); } min(): T { var minNum = this.list[0]; for (var i = 0; i < this.list.
length; i++) { if (minNum > this.list[i]) { minNum = this.list[i]; } } return
minNum; } } // Instantiation class And a class of T The type of representation is number var m1=new MinClas<number>(); m1.add(11)
; m1.add(3); m1.add(2); alert(m1.min()) // Instantiation class And a class of T The type of representation is string var m2 =
new MinClas<string>(); m2.add("b"); m2.add("k"); m2.add("v"); alert(m2.min());
<>4. Function definition
// Function declaration function fun5<T>(name:T):T{ return name } // Function expression let fun6 = function<A>
(name:A):A{ return name; } //ES6 let fun7 =<U>(name:U):U => name;
<>5 generic interface

<>5.1 Function type interface
interface ConfigFn{ (value1:string,value2:string):string; } var setData:
ConfigFn=function(value1:string,value2:string):string{ return value1+value2; }
setData('name',' Zhang San ');
If you want to support return at the same time string,number Type interface , The above function interface does not meet the requirements

<>5.2 generic interface (1)

Defining generics in interfaces
interface ConfigFn{ <T>(value:T):T; } var getData:ConfigFn=function<T>(value:T)
:T{ return value; } getData<string>(' Zhang San '); // getData<string>(1243); // error
<>5.3 generic interface (2)
interface ConfigFn<T> { (value: T): T; } function getData<T>(value: T): T {
return value; } var myGetData: ConfigFn<string> = getData; myGetData("20");
/* correct */ // myGetData(20) // error // Interface interface Search{ <T>(a:T,b:T):boolean; } //
Interface Search representative Yes 2 Parameters , The type is any type , And the parameter types are consistent , The interface returns boolean value // Here's how to use the interface : let f4:Search
= function<T>(str1:T,str2:T):boolean{ //void No return value return str1==str2; //true/false
} f4<number>(123,456)
<>5.4 The application of generics in classes
class A2<T>{ n:T; // Represents the type of the property constructor(num:T){ // The type of value this.n = num; } action(x
:T):T{ return x } }; var a2 = new A2<string>('abc'); // instantiation a2.action('3')
<>TypeScript Generic class A generic class that takes a class as a parameter type

Use the class as a parameter to constrain the type of data passed in
class User{ username:string | undefined; pasword:string | undefined;
constructor(username:string,pasword:string) { this.username = username; this.
pasword= pasword; } } class MysqlDb{ allUser:any[] = []; add(user:User):boolean{
console.log(user); this.allUser.push(user) return true; } getUsers(){ console.
log(this.allUser) } } var u1=new User(' Zhang San ','123456'); var u2=new User(' Li Si ',
'123456'); var Db=new MysqlDb(); Db.add(u1); Db.add(u2); Db.getUsers();
<>2 Array generics

// Array generics You can also use array generics Array To represent an array
let arr: Array = [1, ‘1’, true, 3, 5]; //number[]

<>3 Defines the type of return value T

We add the , among T A type used to refer to any input ,
Input at the end value: T And output Array You can use the .
function createArray2<T>(length: number, value: T): Array<T> { let result: T[]
= []; for (let i = 0; i < length; i++) { result[i] = value; } return result; }
createArray2<string>(3, 'x');

©2019-2020 Toolsou All rights reserved,
The 11th Blue Bridge Cup python The real topic of the University Group National Games JavaSwing To achieve a simple Lianliankan games 【Spring Source code analysis 】42-@Conditional Detailed explanation element-ui Step on pit record 2019PHP Interview questions ( Continuously updated )PHPJava Misunderstanding —— Method overloading is a manifestation of polymorphism ? First issue 500 100 million , Set up a new Department , What is Tencent going to do ? Google chrome The browser can't open the web page , But what if other browsers can open it ? Regression of dependent variable order categories (R language )【Golang Basic series 10 】Go language On conditional sentences if