TypeScript 泛型编程
泛型是 TypeScript 高级类型的基础,让代码支持多种类型同时保持类型安全,下面梳理核心用法。
泛型函数
使用 <T> 定义类型参数:
TypeScript
function identity<T>(value: T): T {
return value;
}
identity<string>("hello"); // 显式指定类型
identity(42); // 编译器推断 T 为 number
多个类型参数
TypeScript
function pair<T, U>(a: T, b: U): [T, U] {
return [a, b];
}
const p = pair("age", 25); // [string, number]
泛型与数组
TypeScript
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
first([1, 2, 3]); // T 推断为 number
first(["a", "b"]); // T 推断为 string
泛型接口
TypeScript
interface ApiResponse<T> {
code: number;
data: T;
message: string;
}
interface User {
id: string;
name: string;
}
const res: ApiResponse<User> = {
code: 0,
data: { id: "1", name: "Alice" },
message: "ok"
};
泛型函数类型
TypeScript
interface FetchFn {
<T>(url: string): Promise<T>;
}
const fetch: FetchFn = async (url) => {
const res = await window.fetch(url);
return res.json();
};
const user = await fetch<User>("/api/user");
泛型类
TypeScript
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
get size(): number {
return this.items.length;
}
}
const numStack = new Stack<number>();
numStack.push(1);
// numStack.push("a"); // ❌ 类型不兼容
const strStack = new Stack<string>();
strStack.push("hello");
泛型与继承
TypeScript
class Animal {
constructor(public name: string) {}
}
class Dog extends Animal {
bark() { console.log("Woof!"); }
}
class AnimalShelter<T extends Animal> {
constructor(private animals: T[]) {}
findByName(name: string): T | undefined {
return this.animals.find(a => a.name === name);
}
}
const shelter = new AnimalShelter([new Dog("Buddy")]);
const dog = shelter.findByName("Buddy");
// dog?.bark(); // ✅ T 继承了 Animal
泛型工具类型实现
TypeScript
// 简易版 Partial
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
// 简易版 Pick
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type User = { id: string; name: string; email: string; };
type SafeUser = MyPick<User, "id" | "name">;
要点总结
- 泛型用
<T>定义类型参数,让函数/接口/类支持多种类型 - 调用泛型函数时可显式指定类型或让编译器自动推断
- 泛型接口可描述泛型返回值或泛型函数签名
- 泛型类确保类成员类型与实例化时指定的类型一致
extends约束泛型范围,实现类型安全的泛型编程
📝 发现内容有误?点击此处直接编辑