泛型
泛型是为类型提供“参数化”的能力,就像函数参数一样,类型也可以成为参数。在保持类型安全的前提下,编写可复用的代码。
例如在定义函数时,我们不知道传入的类型是什么,我们就可以定义一个泛型参数
泛型函数
ts
function identity<T>(value: T): T {
return value;
}
const str = identity("hello"); // str 类型是 string
const num = identity(123); // num 类型是 number泛型类型
ts
type A<T>=string|number|T
let a:A<boolean>=false泛型接口
ts
interface ApiResponse<T> {
code: number;
data: T;
message?: string;
}
// 使用
const resp: ApiResponse<{ id: number; name: string }> = {
code: 200,
data: { id: 1, name: "Alice" }
};泛型约束
可以对泛型类型加约束,限制泛型必须满足某种条件。
ts
function getLength<T extends { length: number }>(arg: T): number {
return arg.length;
}
getLength("hello"); // ✅ 5
getLength([1, 2, 3]); // ✅ 3
// getLength(123); // ❌ 报错,number 没有 length泛型默认类型
ts
function createArray<T = string>(length: number, value: T): T[] {
return Array(length).fill(value);
}
const arr1 = createArray(3, "a"); // string[]
const arr2 = createArray<number>(3, 0); // number[]