1.泛型函数和泛型接口
function log<T>(value : T) : T{ console.log(value); return value; } log<number>(1); log<string>("1"); log<object>({}); log<string[]>(["1"]) interface Log<T> { (value : T) : T; } let myLog : Log<string>= log; myLog("string"); let myLog1 : Log<number> = log; myLog1(1); let myLog2 : Log<Array<string>> = log; myLog2(["1"]);2.泛型类与泛型约束 注意泛型不能约束静态成员
class Log1<T> { run (value : T) { console.log(value); return value; } } let log1 = new Log1<number>(); log1.run(1);3.当泛型不传时,可以是任意类型
let log2 = new Log1(); log2.run(1); log2.run("1"); log2.run({});4.泛型继承接口,实现只能传保护length的值
interface Length { length : number } function Log4<T extends Length> ( value : T) : T{ console.log(value.length) return value; } Log4({length : 1}); Log4("1"); Log4([1,2,3]);