Translate from one category to a different one

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
}

Answer №1

To simplify the process of copying properties, consider using Typescript's object spread syntax.

For example:

function mapRawDataToViewData (rawData: RawData): ViewData {
  return {
    ...rawData,
    isVisible: Math.random() >= 0.5
  }
}

With this approach, all items from RawData are automatically copied into the returned object, saving you from manually copying them. You only need to add the extra properties specific to ViewData. If you need to override a property from the base (RawData), you can easily do so by modifying it after spreading the base properties like this -

function mapRawDataToViewData (rawData: RawData): ViewData {
  return {
    ...rawData,
    someOtherData: "Overridden value",
    isVisible: Math.random() >= 0.5
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...

How can typescript configurations be imported/exported in a node environment?

I'm encountering difficulties while trying to set up a TypeScript node project and import modules: Below is the structure of my project: /build /src main.ts ...

Transforming the unmanaged value state of Select into a controlled one by altering the component

I am currently working on creating an edit form to update data from a database based on its ID. Here is the code snippet I have been using: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material ...

What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

Retrieve all services within a Fargate Cluster using AWS CDK

Is there a way to retrieve all Services using the Cluster construct in AWS CDK (example in TypeScript but any language)? Here is an example: import { Cluster, FargateService } from '@aws-cdk/aws-ecs'; private updateClusterServices(cluster: Clus ...

How can I display a new module in Angular without navigating to it?

After following the tutorial at https://angular.io/guide/lazy-loading-ngmodules#create-a-feature-module-with-routing I set out to create the following: My goal is to have a dedicated module for all customer-related components accessible through the /cust ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

How to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript Original Array: [ {"Id":"3","DisplayName":"Fax"}, {"Id":"1","DisplayName":"Home"}, {"Id":&quo ...

Retrieve the value from an HTML class using Angular

The Person Object has a field called schoolId, but the School object (not shown here) contains the schoolName. I want to display the schoolName in the table data cell instead of the schoolId from the Person Object. How can I achieve this? <tr *ngFor=& ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

Sending the value of "username" between two components within Angular 2

I have a good understanding of nesting child components within parent components in Angular 2, but I'm a bit unclear on how to pass a single value from one component to another. In my scenario, I need to pass a username from a login component to a cha ...

Error displaying messages from the console.log function within a TypeScript script

My node.js application runs smoothly with "npm run dev" and includes some typescript scripts/files. Nodemon is used to execute my code: This is an excerpt from my package.json file: { "scripts": { "start": "ts-node ./src/ind ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

Error message: Material Design UI - The type 'string' cannot be assigned to the type Icon

I am currently working on a component that is responsible for returning the specific icon based on the prop that is passed. Here is a simplified version of how it works in my application: import * as icons from "@mui/icons-material"; interface I ...

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

Is it possible to optimize the performance of my React and TypeScript project with the help of webpack?

I am working on a massive project that takes 6 to 8 minutes to load when I run npm start. Is there a way to speed up the loading process by first displaying the sign-in page and then loading everything else? ...

How can you customize the appearance of the filledInput component within a TextField component in Material UI?

I need some guidance on how to change the color of the FilledInput component within a TextField. Unlike InputProps, FilledInputProps are not directly accessible for styling with classes. Any suggestions on how I can customize the styling of the FilledInpu ...

How might the issue of update activation affecting lazy loading in an Angular PWA app specifically manifest itself?

I am looking for a way to trigger an update activation in my Angular PWA app. I came across a note in the documentation from the official Angular website (https://angular.io/guide/service-worker-communications) that says: "Doing this could break lazy-load ...

Testing the receiveMessage function in SQS using Jest unit tests

Struggling to find the right approach for unit testing this function. I almost have it, but can't quite nail it down. Take a look at the function below: receiveMessage(callback: Function): any { this.sqs.receiveMessage( this.params, ...