Weather model
- TypeScript course
- Intermediate
- Lesson 81/89
- 5 min
Design weather data types.
What is a weather model?
In a weather app, the data model is designed first. Weather data contains city name, temperature, and condition (sunny, rainy). In TypeScript you define this structure with an interface. This way all weather records share the same shape and missing fields are caught at compile time.
interface Weather {
city: string;
temperature: number;
condition: string;
}Temperature and condition types
Each field of the model is chosen with an appropriate type. City name is string, temperature is number, and condition is usually string or a literal union type. Type selection provides compile-time checking and prevents wrong data assignment.
interface Weather {
city: string;
temperature: number;
condition: string;
}Practice Create a weather object
Define a Hava interface: sehir: string, sicaklik: number, durum: string. Create a Hava object named h with city "İstanbul", temperature 22, and condition "güneşli". Print h.sehir with console.log.
Starter code
// Hava interface tanımla
// sehir, sicaklik, durum alanları olsun
// h adında bir Hava nesnesi oluştur
// h.sehir yazdırSample solution
interface Hava {
sehir: string;
sicaklik: number;
durum: string;
}
const h: Hava = { sehir: "İstanbul", sicaklik: 22, durum: "güneşli" };
console.log(h.sehir);Expected output
İstanbul
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the most suitable structure for holding weather data?
- A single number variable
- A nested function definition
- An interface containing temperature, city, and condition Correct answer
- Only a string array
Explanation: Weather data contains multiple fields, so defining it with an interface is most suitable; each field is declared with its own type.
2 Temperature field type
interface Hava {
sehir: string;
sicaklik: ____;
durum: string;
}
interface Hava {
sehir: string;
sicaklik: number;
durum: string;
}
Explanation: Since temperature is a numeric value, the sicaklik field is defined as number.
3 Weather model parts
| Term | Meaning |
|---|---|
sehir |
City name |
sicaklik |
Temperature value |
durum |
Weather condition description |
Hava |
Main model name |