TypeScript_ Generics

// generic: a class, an interface, the function of the uncertainty (unknown) support data types, increase reusability of classes, interfaces, function code, reduce redundancy 
// developer may be used according to different data types the same interface, the class or function 


/ * * 
* the following example * Get a predetermined minimum value function, when the corresponding set of numbers is eligible, has to prepare a set of functions for obtaining the minimum number, * when set to a string , need to further define a set of functions for the character string acquired minimum worth, * then it will cause redundancy code, the code reusability low * as follows:
* / function MIN1 (List: Number []): Number { the let MINRES: Number = List [0 ]; list.forEach ((Item, index) => { IF (Item < MINRES) { MINRES = Item; } }); return MINRES; } functionMIN2 (List: String []): {String the let MINRES: String = List [0 ]; list.forEach ((Item, index) => { IF (Item < MINRES) { MINRES = Item; } }); return MINRES ; } the console.log (MIN1 ([ 9,3,4,2,5])); // output 2 the console.log (MIN2 ([ 'R & lt', 'A', 'C', 'B', ' H ',' f '])); // output a / * * * the use of generics can solve the above problems * incoming and return the data type is determined by the function call themselves, without the need to write redundant code * T represents unknown type, can also be used with other custom words or letters * / function min <T> (List: T []): {T the let MINRES:T = list[0]; list.forEach((item, index)=>{ if(item < minRes){ minRes = item; } }); return minRes; } console.log(min1([9,3,4,2,5])); // 输出 2 console.log(min2(['r','a','c','b','h','f'])); // 输出 a /** * 泛型类 */ class Operation<T>{ list:T[] = []; constructor(){} add(v:T):void{ this.list.push (V); } the getList (): T [] { return the this .list; } min (): T { the let MINRES: T = the this .list [0 ]; the this .list.forEach ((Item, index ) => { IF (Item < MINRES) { MINRES = Item; } }); return MINRES; } } // the specified type to a number type the let = O new new Operation <number> (); // instantiate the class, and to specify a class T is the number represented by the type // o.add ( 'E'); // given, the type number must o.add (6I ()); // Output: b

 

Guess you like

Origin www.cnblogs.com/mandy-dyf/p/11727515.html