泛型
泛型,最简单的理解:泛指的类型。(类似函数中的形参与实参)
函数中的泛型使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function join(first: string | number, second: string | number) { return `${first}${second}` } join('jspang', 1);
function join<JSPang>(first: JSPang, second: JSPang) { return `${first}${second}` }
join<string>('jspang', '123'); join<number>(11, 22);
function myFun<ANY>(params:ANY[]) { return params } myFun<string>(['a', 'b'])
function join2<T,P>(first: T, second: P) { return `${first}${second}` }
join2<string,number>('jspang', 123); join2<number, string>(11, '22'); join2(11, '22');
|
class类中使用泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class SelectGirl { constructor(private girls: string[] | number[]) { } getGirl(index: number): string | number { return this.girls[index] } }
class SelectGirl<T> { constructor(private girls: T[]) { } getGirl(index: number): T { return this.girls[index] } }
const selectGirl = new SelectGirl<number>([101, 102, 103]) console.log(selectGirl.getGirl(1))
interface Girl { name: string } class SelectGirl2<T extends Girl> { constructor(private girls: T[]) { } getGirl(index: number): string { return this.girls[index].name } }
const selectGirl2 = new SelectGirl2([ {name: '大脚1'}, {name: '大脚2'}, {name: '大脚3'} ])
console.log(selectGirl2.getGirl(1))
|