五、typescript泛型
在定义函数或是类时,遇到类型不明确就可以使用泛型;
定义单个泛型:
这里的泛型使用T也可以使用其他;
1 function aaa<T>(a:T):T{ 2 return a; 3 } 4 //使用: 5 console.log(aaa(10));//不指定泛型,TS可以自动对类型进行推断 10 6 console.log(aaa<string>("hello"));//指定泛型 hello
定义多个泛型
1 function bbb<K,T>(a:K,b:T):T{ 2 return b; 3 } 4 console.log(bbb<string,number>("hello",123123));//指定泛型 123123
泛型指定范围
1 //T extends inter 表示T必须是inter实现类 or 子类 2 function CCC<T extends inter>(a: T): number { 3 return a.name.length; 4 } 5 interface inter { 6 name: string; 7 } 8 class XX implements inter { 9 name: string; 10 constructor(name: string) { 11 this.name = name 12 } 13 } 14 const xx = new XX("JJJ"); 15 console.log(CCC(xx));//指定泛型 打印结果3
类中发泛型使用:
1 class DD<T>{ 2 name: T; 3 constructor(name: T) { 4 this.name = name 5 } 6 } 7 const yy = new DD<string>("aaaa"); 8 console.log(yy);//{name: 'aaaa'}
博客园地址:https://www.cnblogs.com/lixiuming521125/

浙公网安备 33010602011771号