泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。
// 基础示例:原样返回输入值
function identity<T>(arg: T): T {
return arg;
}
在实际开发中,后端返回的数据结构通常是固定的,比如 { 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 属性
});