思维导图

定义:把类型作为一个特殊的参数传进去
泛型类
class EagleChinaWu<T> {
private value: T;
getValue(): T {
return this.value;
}
setValue(value: T) {
this.value = value;
}
}
let ecw = new EagleChinaWu<string>();
ecw.setValue('WeChat');
泛型函数
function EagleChinaWu<T>(arg: T): T {
return arg;
}
let ecw: string = EagleChinaWu('WeChat');
function concatArr<T>(...arg: T[][]): T[] {
let result: T[] = [];
arg.forEach(item => {
result = result.concat(item);
});
return result;
}
let ecw = concatArr<string>(
['Eagle'], ['China'], ['Wu']
);
console.log(ecw);
泛型构造器
class EagleChinaWu<T> {
private ecw: T;
constructor(ecw: T) {
this.ecw = ecw;
}
show() {
console.log(this.ecw);
}
}
let ecw = new EagleChinaWu('WeChat');
泛型extends:限定范围
class EagleChinaWu<T extends Date> {
private ecw: T;
constructor(ecw: T) {
this.ecw = ecw;
}
show() {
console.log(this.ecw);
}
}
class ForkDate extends Date { }
let ecw = new EagleChinaWu(new Date());
let ecw2 = new EagleChinaWu(new ForkDate());