一:单个泛型的定义
function join<T>(first: T, second: T) {return `${first}${second}`;}join <string> ("jspang", ".com"); // 参数只能传string类型join <number> (1, 2); // 参数只能传number类型
二:数组泛型:可以规定传入数组元素的数据类型。
// 第一种写法function join<T>(arr: Array<T>) {return arr;}console.log(join <number> ([1,2])); // [1,2]// 第二种写法function join<T>(arr: T[]) {return arr;}
三:多个泛型
function join<T, P>(first: T, second: P) {return `${first}${second}`;}join <number, string> (1, '2');
四:类的泛型
class getHero<T>{constructor(private hero: T[]){}geth(index: number): T{return this.hero[index]}}let h = new getHero(['james', 'westbrook', 'curry'])console.log(h.geth(1)) // westbrooklet h2 = new getHero<number>([1,2,3,4])console.log(h2.geth(1)) // 2
1、泛型的继承
需要对泛型定义有一定的规范,例如需要传入数组,每个数组元素都是一个包含name属性的对象。
interface Hero{name: string}class getHero<T extends Hero>{constructor(private hero: T[]){}geth(index: number): string{return this.hero[index].name}}let h = new getHero([{ name: 'james' },{ name: 'westbrook'},{ name: 'curry'}])console.log(h.geth(1)) // westbrook
2、泛型的约束
现在的泛型可以是任意类型,可以是对象、字符串、布尔、数字都是可以的。但你现在要求这个泛型必须是string或者number类型。
interface Hero{name: string}class getHero<T extends number | string>{constructor(private hero: T[]){}geth(index: number): T{return this.hero[index]}}let h = new getHero(['james', 'westbrook', 'curry'])console.log(h.geth(1)) // westbrook
