1. 泛型的定义
function identity(arg: number): number {
return arg;
}
泛型指在用户可以使用自己的组件并可以使用自己的类型;
//数组增删改
class changeArr<T> {
private arr: T[];
constructor(){
this.arr = [];
}
add(item: T) {
this.arr.push(item)
}
delete(item: T){
this.arr.splice(this.arr.findIndex(i => item === i), 1)
}
replace(item: T, item2: T){
this.arr.splice(this.arr.findIndex(i => item === i), 1, item2)
}
}
当然any类型可以通用,它允许传入任何类型的参数,以及使用任何类型的属性和方法,这会引起一些问题:
class changeArr2{
private arr: any[];
constructor(){
this.arr = [];
}
add(item: any) {
this.arr.push(item)
}
delete(item: any){
this.arr.splice(this.arr.findIndex(i => item === i), 1)
}
replace(item: any, item2: any){
this.arr.splice(this.arr.findIndex(i => item === i), 1, item2)
}
}
let ex = new changeArr2();
ex.add(2);
console.log(ex.arr[0].substr(0,1)); //error
它会报运行时错误,但不指不出任何具体的内容,更重要的是,编译器没有给出任何类型不匹配的编译时错误。
2.泛型约束
顾名思义就是约束泛型的数据类型
简单约束
//规定这能传入[] 类型
function sort<T extends []>(arr: T): T{
return arr.sort((a,b) => a-b);
}
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}
使用类型参数来约束
function getValue<T, U extend keyof T>(obj: T, key: T){
return obj[key]
}
let a = {a: 1, b: 2, c: 3}
getValue(a,"a");
getValue(a, "d");//error 提示
//Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c" .
使用类的泛型约束
class BeeKeeper {
hasMask: boolean;
}
class ZooKeeper {
nametag: string;
}
class Animal {
numLegs: number;
}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
return new c();
}
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;