ts-- Generics

// Generics: software engineering, we must not only create good agreement defined API, but also consider the reusability of components to be able to support not only current data type, but also to support future data types
// generic interface method is reusability class solutions and support for non-specific data types
// any abandoned the type checking, incoming and return types can not use the same generic T can make to make the same type of return and outgoing
function getDate<T>(value: T): T {
    return value;
}
getDate<number>(123);

// generic class
class minClass {
    public list: number[] = [];
    add(num: number) {
        this.list.push(num);
    }
    min():number{
        was my this.list umber = [0];
        for (let i = 0; i <this. list.length; i++) {
            if(minNumber>this.list[i]){
                minNumber=this.list[i];
            }
            
        }
        my return umber;
    }
}
var m=new minClass();
m.add(2);
m.add(21);
m.add(12);
m.add(1);
console.log(m.min());

class MinClass<T> {
    public list:T[]=[];
    add(value:T){
        this.list.push(value);
    }
    min (): {T
        was my this.list umber = [0];
        for (let i = 0; i <this. list.length; i++) {
            if(minNumber>this.list[i]){
                minNumber=this.list[i];
            }
            
        }
        my return umber;
    }
}
var m1 = new MinClass <number> (); // instantiate the class, and developed a number of type T represents

m1.add(3);

Guess you like

Origin www.cnblogs.com/xbzxx/p/11986983.html