Data transform
- TypeScript course
- Intermediate
- Lesson 83/89
- 5 min
Transform the API response into the internal model.
What is data transformation?
Converting raw data from the API into the application's internal model is called transformation. A function takes the API response type as a parameter and returns the internal model type. This keeps external data separate from internal data, and even if the API changes, the internal model stays stable.
function transform(r: ApiResponse): Weather {
return { city: r.city, temperature: r.temperature, condition: "-" };
}Field mapping in transformation
Inside the transform function, each field of the API response is copied to the corresponding field of the internal model. The r.city value is assigned to Weather.city. If the internal model contains a field not in the API, a default value is provided during transformation.
function transform(r: ApiResponse): Weather {
return {
city: r.city,
temperature: r.temperature,
condition: "unknown"
};
}Practice donustur function
Define ApiYanit and Hava interfaces: both contain sehir: string and sicaklik: number. The donustur function should be (y: ApiYanit): Hava and return { sehir: y.sehir, sicaklik: y.sicaklik }. Print the .sehir field of the result of calling donustur({ sehir: "Ankara", sicaklik: 18 }) with console.log.
Starter code
// ApiYanit ve Hava interface tanımla
// donustur fonksiyonu ApiYanit alıp Hava dönsün
// sehir ve sicaklik kopyalansın
// donustur ile çağırıp sehir yazdırSample solution
interface ApiYanit { sehir: string; sicaklik: number; }
interface Hava { sehir: string; sicaklik: number; }
function donustur(y: ApiYanit): Hava {
return { sehir: y.sehir, sicaklik: y.sicaklik };
}
const h = donustur({ sehir: "Ankara", sicaklik: 18 });
console.log(h.sehir);Expected output
Ankara
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is used to convert an API response to the internal model?
- console.log
- A transform function Correct answer
- typeof operator
- interface declaration
Explanation: A transform function takes the API response type and returns the internal model type; this keeps external and internal data separate.
2 Parameter variable access
function donustur(y: ApiYanit): Hava {
return { sehir: ____.sehir, sicaklik: y.sicaklik };
}
function donustur(y: ApiYanit): Hava {
return { sehir: y.sehir, sicaklik: y.sicaklik };
}
Explanation: In the transform function the parameter variable is y; fields are accessed as y.sehir.
3 Transformation concepts
| Term | Meaning |
|---|---|
donustur |
Transform function |
map |
Array transform method |
Hava |
Internal model type |
ApiYanit |
External source type |