在 TypeScript 中,泛型是一种用于创建可重用代码的工具。泛型允许你在编写代码时不指定具体的类型,而是在使用代码时再指定类型。 这使得代码更加灵活和可重用。
泛型的基本使用
明确的传入类型
function sum<Type>(num: Type): Type {
return num
}
// 1.调用方式一: 明确的传入类型
sum<number>(20)
sum<{name: string}>({name: "jk"})
sum<any[]>(["abc"])
类型推导
function identity<T>(arg: T): T {
return arg;
}
const result = identity("hello");
console.log(result); // 输出 "hello"
由于我们传递的是一个字符串,因此T被推断为hello字面量类型。
泛型接受类型参数
function foo<T, E, O>(arg1: T, arg2: E, arg3?: O, ...args: T[]) {
}
foo<number, string, boolean>(10, "abc", true)
泛型接口的使用
interface IPerson<T1 = number, T2 = number> {
name: T1
age: T2
}
const p: IPerson<string,number> = {
name: "jk",
age: 18
}
interface IPerson<T1 = number, T2 = number>设置泛型的默认类型,后续使用时可以通过<>传入类型参数。
泛型类的使用
class Point<T> {
x: T
y: T
z: T
constructor(x: T, y: T, z: T) {
this.x = x
this.y = y
this.z = y
}
}
const p1 = new Point("1.33.2", "2.22.3", "4.22.1")
const p2 = new Point<string>("1.33.2", "2.22.3", "4.22.1")
const p3: Point<string> = new Point("1.33.2", "2.22.3", "4.22.1")
const names1: string[] = ["abc", "cba", "nba"]
const names2: Array<string> = ["abc", "cba", "nba"] // 不推荐(react jsx <>)
泛型的类型约束
泛型的类型约束可以通过extends关键字来实现。
例如,我们可以定义一个泛型函数foo,它接受一个类型参数T,并要求 T必须是 number或 string类型:
function foo<T extends number | string>(arg: T) {
console.log(arg);
}
foo(10); // 输出:10
foo("abc"); // 输出:abc
foo(true); // 报错:类型“boolean”的参数不能赋给类型“string | number”的参数。
interface ILength {
length: number
}
function getLength<T extends ILength>(arg: T) { //T extends ILength代表 一定能取到arg.length
return arg.length
}
getLength("abc")
getLength(["abc", "cba"])
getLength({ length: 100 })
这个时候参数只能arg.length有值的情况,比如字符串、数组、还有有length属性的对象。所以起到了泛型约束的效果。