泛型
在定义函数或者类时,如果遇到类型不明确的情况就可以使用泛型。
方法泛型
function sayHello<T>(msg: T): T {
return msg;
}
// 指定泛型调用
sayHello<string>("你好世界");
// 运用类型推断缩写
sayHello("你好世界");
类/接口泛型
class MyClass<T> {
name: T;
constructor(name: T) {
this.name = name;
}
}
泛型上限
interface Inter {
length: number;
}
function fun3<T extends Inter>(a: T): number {
return a.length;
}
最后更新于
这有帮助吗?