۱۲
پروژه ۲: اپ هواشناسی با TypeScript
یک اپلیکیشن هواشناسی واقعی با استفاده از API و تایپبندی دادههای دریافتی.
پیشنمایش پروژه
کد کامل پروژه
قدرت اصلی تایپاسکریپت اینجا مشخص میشه که برای جواب API یه `interface` تعریف میکنیم و مطمئن میشیم که دادهها همون چیزی هستن که انتظار داریم.
weather.ts
// 1. تعریف اینترفیس برای شکل دادههای دریافتی از API
interface WeatherData {
name: string;
main: {
temp: number;
};
weather: {
description: string;
}[];
}
// 2. گرفتن عناصر DOM
const apiKey = 'YOUR_OPENWEATHERMAP_API_KEY'; // کلید API خود را اینجا قرار دهید
const cityInput = document.getElementById('city-input') as HTMLInputElement;
const searchBtn = document.getElementById('search-btn') as HTMLButtonElement;
const weatherInfo = document.getElementById('weather-info') as HTMLDivElement;
// 3. تابع اصلی برای گرفتن و نمایش اطلاعات
async function getWeather(city: string): Promise<void> {
if (!city) {
alert('لطفا اسم شهر را وارد کنید.');
return;
}
weatherInfo.innerHTML = `<p>در حال دریافت اطلاعات...</p>`;
weatherInfo.classList.remove('hidden');
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric&lang=fa`;
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('شهر مورد نظر پیدا نشد!');
}
const data: WeatherData = await response.json();
displayWeather(data);
} catch (error) {
if (error instanceof Error) {
weatherInfo.innerHTML = `<p class="text-red-500">${error.message}</p>`;
}
}
}
function displayWeather(data: WeatherData): void {
const { name, main, weather } = data;
weatherInfo.innerHTML = `
<h3 class="text-2xl font-bold">${name}</h3>
<p class="text-4xl font-bold my-2">${Math.round(main.temp)}°C</p>
<p class="text-lg text-muted-foreground">${weather[0].description}</p>
`;
}
// 4. اضافه کردن رویدادها
searchBtn.addEventListener('click', () => {
getWeather(cityInput.value);
});
cityInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
getWeather(cityInput.value);
}
});
آفرین! دوره TypeScript تموم شد! 🏆
شما با موفقیت این دوره رو به پایان رسوندین و حالا میتونید پروژههای جاوااسکریپت بزرگ و پیچیده رو با اطمینان و امنیت خیلی بیشتری بنویسید. این مهارت در بازار کار امروز فوقالعاده ارزشمنده. موفق باشی!