欢迎扫码,加作者微信

TypeScript 泛型 (Generics) 进阶指南:让代码更灵活

2026-02-15 09:00:00
2026-02-15 09:00:00

一、 什么是泛型?

泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。


// 基础示例:原样返回输入值
function identity<T>(arg: T): T {
    return arg;
}

二、 实战:封装 Axios 请求

在实际开发中,后端返回的数据结构通常是固定的,比如 { code: 200, data: T, msg: string }。我们可以利用泛型来定义这个结构:


interface ApiResponse<T> {
    code: number;
    msg: string;
    data: T;
}

async function request<T>(url: string): Promise<ApiResponse<T>> {
const response = await fetch(url);
return response.json();
}

// 使用时指定具体的 User 类型
interface User {
id: number;
name: string;
}

request<User>('/api/user/1').then(res => {
console.log(res.data.name); // TS 此时能正确提示 name 属性
});

文章目录
Copyright © 2026 湘ICP备2025142407号
🎉 今日第 1 位访客 📊 年访问量 0 💝 累计赞赏 1000+