泛型:宽泛的类型
泛型-函数
知道确定的参数的类型以及返回值的类型
function test(a: string, b: number): string{
return a + b
}
test("key", 123);
函数的参数和返回值我们不确定的话,就先用一个宽泛的类型约束
类型用大写的单个字母占位,在函数名后面用尖括号<>传递
function test<K, V>(a: K, b: V): K{
return a + b
}
test("key", 123);
泛型-对象
class Person{
name: string;
constructor(name: string){
this.name = name;
}
getName(): string{
return this.name;
}
}
const p = new Person("pitaya");
const n = p.getName();
对象属性和方法中的参数与返回值我们不确定,也用一个宽泛的类型来约束
class Person<N>{
name: N;
constructor(name: N){
this.name = name;
}
getName(): N {
return this.name;
}
}
const p = new Person(true);
const n = p.getName();
泛型默认类型
class Person<N = string>{}
泛型约束:
extends 约束泛型的范围
希望定义的泛型必须满足某一个必要条件
// 希望getLength这个方法获取到参数的长度
function getLength<T extends { length: number }>(arg: T): number{
return arg.length;
}
// getLength(true);
getLength("hello");
getLength({
length: 10,
name: "pig",
});
希望定义的泛型必须满足
interface IbasicInfo{
id: number;
name: string;
}
interface IStudentsInfo extends IbasicInfo{
gender: number;
}
const studentA: IStudentsInfo = {
id: 123,
name: "hello",
gender: 1,
}
1189

被折叠的 条评论
为什么被折叠?



