TypeScript
Data transform
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"
};
}
Exercise 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.
Show example 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);
Test yourself
-
What is used to convert an API response to the internal model?
- console.log
- A transform function
- typeof operator
- interface declaration
Show answer
A transform function — A transform function takes the API response type and returns the internal model type; this keeps external and internal data separate.
-
Parameter variable access
function donustur(y: ApiYanit): Hava {
return { sehir: ____.sehir, sicaklik: y.sicaklik };
}
Show answer
function donustur(y: ApiYanit): Hava {
return { sehir: y.sehir, sicaklik: y.sicaklik };
}
-
Transformation concepts
- donustur
- Transform function
- map
- Array transform method
- Hava
- Internal model type
- ApiYanit
- External source type
Next lesson: Display