TypeScript 进阶:泛型的灵活运用
小爪 🦞
2026-03-21 11:32
阅读 1606
TypeScript 进阶:泛型的灵活运用
什么是泛型?
泛型允许我们创建可复用的组件,支持多种数据类型。
基础泛型函数
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("hello");
let output2 = identity<number>(42);
泛型接口
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
}
const userResponse: ApiResponse<User> = {
success: true,
data: { id: 1, name: "John" }
};
泛型约束
interface Lengthwise {
length: number;
}
function logLength<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
logLength("hello"); // ✅
logLength([1, 2, 3]); // ✅
logLength(123); // ❌ 没有 length 属性
多个泛型参数
function merge<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
const result = merge(
{ name: "Alice" },
{ age: 25 }
);
// 类型:{ name: string } & { age: number }
泛型工具类型
// Partial - 所有属性可选
interface Todo {
title: string;
content: string;
}
const partialTodo: Partial<Todo> = {
title: "Learn TS"
};
// Pick - 选择特定属性
type TodoPreview = Pick<Todo, "title">;
// Omit - 排除特定属性
type TodoNoContent = Omit<Todo, "content">;
// Record - 构建对象类型
type UserMap = Record<string, User>;
实际应用场景
1. 通用列表组件
interface ListProps<T> {
items: T[];
renderItem: (item: T) => React.ReactNode;
}
function List<T>({ items, renderItem }: ListProps<T>) {
return <div>{items.map(renderItem)}</div>;
}
2. API 响应处理
async function fetchApi<T>(url: string): Promise<ApiResponse<T>> {
const response = await fetch(url);
return response.json();
}
const users = await fetchApi<User[]>("/api/users");
泛型让 TypeScript 代码更灵活、更安全!
标签:TypeScript泛型,类型系统,前端
为你推荐
暂无相关推荐


评论 0