泛型 即 将类型参数化, 由调用者 决定应该是什么类型, 当你确定参数的类型的时候 就不一定要用 泛型了
//定义函数时 我不决定这些参数的类型//而是让调用者以参数的形式告知 我这里的函数参数应该是什么类型function sum<Type>(num:Type):Type{return num}//使用的时候再决定它的类型sum<number>(20)function identity<Type>(arg: Type): Type {return arg;}let myIdentity: <Type>(arg: Type) => Type = identity;interface Gener{<T>(arg:T):T}function id<T>(arg:T):T{return arg}let myI:Gener = id
常见的名称/使用习惯
T : Type缩写 类型
K、V : key和value 的缩写, 键值对
E : Element的缩写, 元素
O : Object的缩写,对象
function foo<T,E,O>(arg1:T,arg2:E,arg3:O){}foo<number,string,boolean>(10,"abc",true)
//遍历对象索引function foo<O>(args:O){for(let key in args){console.log(key)}}foo<object>({test:'123',abc:'123213'})//遍历数组function foo1<T>(...args:T[]){for(let key of args){console.log(key)}}foo1<number>(10,20,30)
接口使用泛型
//可以定义默认类型interface IPerson<T1=string,T2=number>{name:T1age:T2}const p:IPerson<string,number> = {name:'why',age:18}
类与泛型
//类与泛型class Point<T>{x:Ty:Tz:Tconstructor(x:T,y:T,z:T){this.x = xthis.y = ythis.z = z}}//类型推导const p1 = new Point("1.33.2","2.22.3","4.22.1")//显式声明const p2 = new Point<string>("1.33.2","123","4.22.1")const p3:Point<string> = new Point("1.33.2","123","4.22.1")
泛型的类型限制
//泛型的类型约束//通过extends 对类型进行限制interface ILength{length:number}function getLength<T extends ILength>(arg:T){return arg.length}getLength("123")
泛型继承
interface Props{length:number}const calcArray = <T extends Props,>(data:T):number=>{return data.length
