async function fetchData<T>(url: string): Promise<T> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data: T = await response.json();
return data;
} catch (error) {
if (error instanceof Error) {
console.error('Fetch failed:', error.message);
}
throw error;
}
}
// Usage
interface User {
id: number;
name: string;
}
const user = await fetchData<User>('/api/user/1');