API response type
- TypeScript course
- Intermediate
- Lesson 82/89
- 5 min
Write the API response type with interface.
What is an API response type?
Data coming from a weather API usually has a fixed structure. You define this structure with an interface. Sometimes the API may omit some fields; in that case you mark those fields as optional. This way both real API data and incomplete responses are handled type-safely.
interface ApiResponse {
city: string;
temperature: number;
humidity?: number;
}Required and optional fields
Fields always present in an API response are required and declared with :. Fields that may sometimes be missing are made optional with ?. For example, city always arrives but humidity may be absent in some responses. This separation preserves data consistency.
interface ApiResponse {
city: string; // required
temperature: number; // required
humidity?: number; // optional
}Practice API response interface
Define an ApiYanit interface: sehir: string and sicaklik: number required, nem?: number optional. Create an ApiYanit object named y with only sehir: "İzmir" and sicaklik: 25. Print y.sehir with console.log.
Starter code
// ApiYanit interface tanımla
// sehir ve sicaklik zorunlu, nem opsiyonel olsun
// y nesnesi oluştur, sadece sehir ve sicaklik ver
// y.sehir yazdırSample solution
interface ApiYanit {
sehir: string;
sicaklik: number;
nem?: number;
}
const y: ApiYanit = { sehir: "İzmir", sicaklik: 25 };
console.log(y.sehir);Expected output
İzmir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a field that may sometimes be absent in an API response marked?
- With void
- With the const keyword
- With readonly
- Made optional with ? Correct answer
Explanation: Optional fields are marked with ?; if the field is absent it is accepted as undefined and causes no compile error.
2 Optional field marker
interface ApiYanit {
sehir: string;
nem____: number;
}
interface ApiYanit {
sehir: string;
nem?: number;
}
Explanation: To declare an optional field, a ? is placed after the field name; if absent, it is accepted as undefined.
3 API response concepts
| Term | Meaning |
|---|---|
interface |
Structure definition |
? |
Optional field marker |
nem |
Humidity field |
yanit |
API return data |