Generics

Generic: In software engineering, code reuse must be considered. Components can not only support current data types, but also support future data types

Generics is to solve the reusability of class interface methods and support for unspecified data types (type verification)

Generics can support unspecified data types. Requirements: The parameters of infection are the same as those returned

Generic function

 

//   T means generic, what kind of 
function is determined when calling this method getDate <T> (value: T): T {
     return value; 
} 

getDate <number> (123 ); 
getDate <string> ('123 ');

 

Generic class

 

class Min <T> { 
    public list: T [] = []; 
    constructor () { 

    } 
    add (value: T) { 
        this .list.push (value); 
    } 

    min (): T { 
        var minNum = this .list [0 ];
         this .list.forEach ((item) => {
             if (item < minNum) { 
                minNum = item; 
            } 
        }) 
        return minNum; 
    } 
} 

var m = new Min <number> (); // instantiate Class and the type of the T represented by the class is number
m.add(4);
m.add(6);
m.add(8);
alert(m.min());  //4

 

Generic interface

 

// 方式1
interface ConfigFn<T>{
    (value:T):T;
}

function getData<T>(value:T):T{
    return value;
}

getData<string>('Tom');
// 方式2
interface ConfigFn2{
    <T>(value:T):T;
}

var getData2:ConfigFn2 = function<T>(value:T):T{
    return value;
}

getData2<number>(12);

 

Guess you like

Origin www.cnblogs.com/webmc/p/12675012.html