// 定义接口Product
interface Product {
id: number;
name: string;
price: number;
}
// 编写泛型函数fetchData
function fetchData<T>(path: string): Promise<{ data: T, status: string }> {
// 模拟通过fetch获取数据
return Promise.resolve({
data: {} as T,
status: 'ok'
});
}
// 调用fetchData函数获取Product类型的数据
fetchData<Product>('/products')
.then(result => {
console.log(`产品名称: ${result.data.name}, 价格: ${result.data.price}`);
})
.catch(error => {
console.error('获取数据失败:', error);
});
类型推断解释
- 泛型参数
T
:在fetchData
函数定义中,<T>
表示一个类型参数。在调用fetchData<Product>('/products')
时,将T
指定为Product
类型。这样,fetchData
函数返回的Promise对象中的data
属性就被推断为Product
类型。
- 接口
Product
:定义了Product
接口,明确了数据应该具有的结构。在fetchData
函数返回值类型中,<T>
的实际类型Product
满足data
属性的类型要求。同时,在处理fetchData
返回结果时,TypeScript知道result.data
的类型是Product
,所以可以安全地访问name
和price
属性。
优势
- 代码复用:
fetchData
函数通过泛型T
可以适用于任何数据类型,而不需要为每种数据类型单独编写获取数据的函数。
- 类型安全:结合接口,TypeScript在编译时就能检查类型是否匹配。如果
fetchData
返回的数据结构与接口Product
不匹配,编译时就会报错,减少运行时错误。
- 可读性:接口和泛型的使用使得代码结构清晰,开发者能清楚知道数据的预期结构和函数的类型参数,提高代码的可维护性。