I often encounter a common issue - how can I efficiently convert one type to another? For instance, extending an object received from the server with UI-specific properties.
interface RawData {
id: number
someOtherData: string
}
interface ViewData extends RawData {
isVisible: boolean
}
const rawData: RawData = getDataFromServer() // Retrieves data of type RawData
const viewData: ViewData = mapRawDataToViewData(rawData)
function mapRawDataToViewData (rawData: RawData): ViewData {
return {
id: rawData.id,
someOtherData: rawData.someOtherData,
isVisible: Math.random() >= 0.5
}
}
The approach above is effective, but managing large objects can become cumbersome, especially when dealing with dynamic server data that may change periodically. Instead of updating just one interface when changes occur, I need to update multiple map functions as well.
In traditional JavaScript, I might use a function like the following. As I adapt the implementation to TypeScript, I wonder if there is a more efficient way. Is it possible to clone all existing properties and include additional ones? What types should be added in the following scenario?
function mapRawDataToViewData (rawData) {
const viewData = copy(rawData) // Produces a non-mutated copy of the original rawData
viewData.isVisible = Math.random() >= 0.5
return viewData
}